#include <bits/stdc++.h>
using namespace std;
const int Nmax=500010;
int N, K, S[Nmax], L[Nmax], Dep[Nmax], P[Nmax][20], G[Nmax], ind[Nmax], ans;
vector<int> adj[Nmax], V[Nmax];
set<int> cadj[Nmax];
int Find(int x) {return G[x]?(G[x]=Find(G[x])):x;}
void Union(int a, int b) {
a=Find(a), b=Find(b);
if(a!=b) G[a]=b;
}
void DFS(int curr, int prev) {
for(int next:adj[curr]) if(next!=prev) {
Dep[next]=Dep[curr]+1;
P[next][0]=curr;
DFS(next, curr);
}
}
int LCA(int u, int v) {
if(Dep[u]<Dep[v]) swap(u, v);
int dif=Dep[u]-Dep[v];
for(int i=0; dif; i++) {
if(dif&1) u=P[u][i];
dif>>=1;
}
if(u!=v) {
for(int i=19; i>=0; i--) {
if(P[u][i] && P[u][i]!=P[v][i]) u=P[u][i], v=P[v][i];
}
u=P[u][0];
}
return u;
}
void DFS2(int curr, int prev) {
for(int i=curr; Dep[i]>Dep[L[S[curr]]]; i=L[S[P[i][0]]]) {
Union(i, P[i][0]);
}
for(int next:adj[curr]) if(next!=prev) DFS2(next, curr);
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(0);
cin>>N>>K;
for(int i=1; i<N; i++) {
int u, v; cin>>u>>v;
adj[u].push_back(v);
adj[v].push_back(u);
}
for(int i=1; i<=N; i++) {
cin>>S[i];
V[S[i]].push_back(i);
}
DFS(1, 0);
for(int i=1; i<=20; i++) {
for(int j=1; j<=N; j++) P[j][i]=P[P[j][i-1]][i-1];
}
for(int i=1; i<=K; i++) {
for(int j:V[i]) {
if(!L[i]) {L[i]=j; continue;}
L[i]=LCA(L[i], j);
}
}
DFS2(1, 0);
for(int i=1; i<=N; i++) Find(i);
for(int i=1; i<=N; i++) if(!G[i]) G[i]=i;
for(int i=1; i<=N; i++) {
for(int j:adj[i]) if(G[i]!=G[j]) cadj[G[i]].insert(G[j]);
}
for(int i=1; i<=N; i++) ans+=(cadj[i].size()==1);
cout<<(ans+1)/2;
return 0;
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
23 ms |
47316 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
23 ms |
47316 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
23 ms |
47316 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
123 ms |
71132 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
23 ms |
47316 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |