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 maxn=200000+10;
vector<int>adj[maxn],allc[maxn];
int n,k,val[maxn],sz[maxn],part[maxn],visc[maxn],vis[maxn],now[maxn],rishe,res;
void calsz(int u,int par=0){
now[u]=rishe;
part[u]=par;
visc[val[u]]=0;
sz[u]=1;
for(auto x:adj[u]){
if(vis[x]==0&&x!=par){
calsz(x,u);
sz[u]+=sz[x];
}
}
}
int findcen(int u,int su,int par=0){
for(auto x:adj[u]){
if(vis[x]==0&&x!=par&&sz[x]*2>su){
return findcen(x,su,u);
}
}
return u;
}
void solve(int u){
if(now[u]==-rishe){
return ;
}
if(now[u]!=rishe){
res=n+2;
return ;
}
if(visc[val[u]]==0){
res++;
visc[val[u]]=1;
for(auto x:allc[val[u]]){
solve(x);
if(res>n){
return ;
}
}
}
now[u]=-rishe;
solve(part[u]);
}
int cent(int u){
int ret=n+1;
calsz(u);
int v=findcen(u,sz[u]);
rishe=v;
calsz(v,v);
res=0;
solve(v);
ret=min(ret,res);
vis[v]=1;
for(auto x:adj[v]){
if(vis[x]==0){
ret=min(ret,cent(x));
}
}
return ret;
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>n>>k;
for(int i=0;i<n-1;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>>val[i];allc[val[i]].push_back(i);
}
cout<<(cent(1)-1)<<endl;
}
# | 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... |