#include <bits/stdc++.h>
using namespace std;
const int nx=5e5+5, kx=19;
int lvl[nx], pa[nx][kx], n, k, u, v, s[nx], l[nx], rem[nx], cnt, on[nx], ed[nx], sg, ans;
vector<int> d[nx], t[nx];
void dfs(int u, int p)
{
lvl[u]=lvl[p+1]; pa[u][0]=p;
for (int i=1; i<kx; i++) pa[u][i]=pa[pa[u][i-1]][i-1];
for (auto v:d[u]) if (v!=p) dfs(v, u);
}
int lca(int u, int v)
{
if (lvl[u]>lvl[v]) swap(u, v);
for (int i=kx-1; i>=0; i--) if (lvl[pa[v][i]]>=lvl[u]) v=pa[v][i];
if (u==v) return u;
for (int i=kx-1; i>=0; i--) if (pa[u][i]!=pa[v][i]) u=pa[u][i], v=pa[v][i];
return pa[u][0];
}
void dfs2(int u, int p)
{
if (l[s[u]]==0) l[s[u]]=u;
else l[s[u]]=lca(l[s[u]], u);
for (auto v:d[u]) if (v!=p) dfs2(v, u);
}
void dfs3(int u, int p)
{
for (auto v:d[u]) if (v!=p) dfs3(v, u);
if (on[s[u]]++==0) cnt++;
cnt-=rem[u];
if (cnt==0&&u!=1) ed[u]=1, sg=1;
}
void dfs4(int u, int p, int c)
{
for (auto v:d[u])
{
if (v==p) continue;
if (on[v])
{
t[c].push_back(v);
dfs4(v, u, v);
if (t[v].empty()) ans++;
}
else dfs4(v, u, c);
}
}
int main()
{
cin.tie(NULL)->sync_with_stdio(false);
cin>>n>>k;
for (int i=1; i<n; i++) cin>>u>>v, d[u].push_back(v), d[v].push_back(u);
for (int i=1; i<=n; i++) cin>>s[i];
dfs(1, 1);
dfs2(1, 1);
for (int i=1; i<=k; i++) rem[l[i]]++;
dfs3(1, 1);
if (!sg) return cout<<0, 0;
dfs4(1, 1, 1);
//for (int i=1; i<=n; i++) cout<<i<<' '<<ed[i]<<'\n';
if (t[1].size()==1) ans++;
cout<<(ans+1)/2;
}
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
10 ms |
31320 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
10 ms |
31320 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
10 ms |
31320 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
65 ms |
41416 KB |
Output is correct |
2 |
Correct |
54 ms |
42844 KB |
Output is correct |
3 |
Incorrect |
10 ms |
31580 KB |
Output isn't correct |
4 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Incorrect |
10 ms |
31320 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |