//#pragma GCC optimize("Ofast,unroll-loops,O3")
//#pragma GCC optimize("avx,avx2,sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,fma,tune=native")
#include<bits/stdc++.h>
//#include<bits/extc++.h>
//#pragma pack(1)
#define fast ios::sync_with_stdio(0); cin.tie(0);
#define int long long
#define pii pair<int,int>
#define x first
#define y second
#define N 200015
using namespace std;
//using namespace __gnu_pbds;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
//typedef tree<int, null_type,less_equal<int>, rb_tree_tag,tree_order_statistics_node_update> order_multiset;
//typedef tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update> order_set;
int n,k,deg[N],cap[N],cnt[N],vis[N],tans=0,now=0;
vector<pii>edge;
vector<pii>g[N];
map<pii,int>mp;
set<int>st;
void dfs(int p){
vis[p]=1; now+=cnt[p]; tans++;
st.insert(p);
for (auto i:g[p]){
if (!vis[i.x]){
dfs(i.x);
}
}
}
signed main(){
fast
cin>>n>>k;
for (int i=1;i<n;i++){
int a,b; cin>>a>>b;
edge.push_back({a,b});
}
for (int i=1;i<=n;i++){
cin>>cap[i];
cnt[cap[i]]++;
}
for (auto i:edge){
if (cap[i.x]==cap[i.y]){
cnt[cap[i.x]]--;
continue;
}
int a=cap[i.x],b=cap[i.y];
if (a>b) swap(a,b);
mp[{a,b}]++;
}
for (auto i:mp){
int a=i.x.x,b=i.x.y;
if (i.y>1){
g[a].push_back({b,i.y});
g[b].push_back({a,i.y});
}
deg[a]+=i.y; deg[b]+=i.y;
}
int ans=n;
for (int i=1;i<=k;i++){
if (cnt[i]==1)
ans=1;
}
queue<int>q;
for (int i=1;i<=k;i++){
if (deg[i]==cnt[i]){
q.push(i);
}
}
while (!q.empty()){
int p=q.front(); q.pop();
vis[p]=1;
for (auto i:g[p]){
deg[i.x]-=i.y;
if (deg[i.x]==cap[i.x])
q.push(i.x);
}
}
for (int i=1;i<=k;i++){
if (!vis[i]){
st.clear();
now=0; tans=0;
dfs(i);
int total=0;
for (auto j:st){
for (auto l:g[j]){
if (st.find(l.x)!=st.end())
total+=l.y;
}
}
total/=2;
if (total==now-1)
ans=min(tans,ans);
}
}
cout<<ans-1<<'\n';
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
3 ms |
4948 KB |
Output is correct |
2 |
Correct |
3 ms |
4948 KB |
Output is correct |
3 |
Correct |
4 ms |
4948 KB |
Output is correct |
4 |
Incorrect |
3 ms |
4948 KB |
Output isn't correct |
5 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
3 ms |
4948 KB |
Output is correct |
2 |
Correct |
3 ms |
4948 KB |
Output is correct |
3 |
Correct |
4 ms |
4948 KB |
Output is correct |
4 |
Incorrect |
3 ms |
4948 KB |
Output isn't correct |
5 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
245 ms |
35020 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
3 ms |
4948 KB |
Output is correct |
2 |
Correct |
3 ms |
4948 KB |
Output is correct |
3 |
Correct |
4 ms |
4948 KB |
Output is correct |
4 |
Incorrect |
3 ms |
4948 KB |
Output isn't correct |
5 |
Halted |
0 ms |
0 KB |
- |