This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include<bits/stdc++.h>
using namespace std;
const int N=5e5+5;
int n,k;
vector<int> adj[N],comp[N];
int sz[N],hv[N],lv[N],hd[N],pa[N];
int a[N];
void dfs(int u,int p=0){
    pa[u]=p;
    sz[u]=1;
    for(auto v:adj[u])if(v!=p){
        lv[v]=lv[u]+1;
        dfs(v,u);
        sz[u]+=sz[v];
        if(sz[v]>sz[hv[u]])hv[u]=v;
    }
}
void hld(int u,int p=0){
    if(!hd[u])hd[u]=u;
    if(hv[u])hd[hv[u]]=hd[u],hld(hv[u],u);
    for(auto v:adj[u])if(v!=p&&v!=hv[u])hld(v,u);
}
int lca(int u,int v){
    while(hd[u]!=hd[v]){
        if(lv[hd[u]]<lv[hd[v]])swap(u,v);
        u=pa[hd[u]];
    }
    return lv[u]<lv[v]?u:v;
}
void pull(int u,int p=0){
    for(auto v:adj[u])if(v!=p){
        pull(v,u);
        a[u]+=a[v];
    }
}
int main(){
    cin.tie(nullptr)->sync_with_stdio(false);
    cin >> n >> k;
    for(int i=1;i<n;i++){
        int u,v;
        cin >> u >> v;
        adj[u].emplace_back(v);
        adj[v].emplace_back(u);
    }
    for(int i=1;i<=n;i++){
        int x;
        cin >> x;
        comp[x].emplace_back(i);
    }
    dfs(1);
    hld(1);
    for(int i=1;i<=k;i++){
        for(int j=1;j<comp[i].size();j++){
            int u=comp[i][j-1],v=comp[i][j];
            a[u]++,a[v]++,a[lca(u,v)]-=2;
        }
    }
    pull(1);
    int ans=0;
    for(int i=2;i<=n;i++)ans+=a[i]==0;
    cout << (ans+1)/2;
}
Compilation message (stderr)
mergers.cpp: In function 'int main()':
mergers.cpp:61:22: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
   61 |         for(int j=1;j<comp[i].size();j++){
      |                     ~^~~~~~~~~~~~~~~| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict  | Execution time | Memory | Grader output | 
|---|
| Fetching results... |