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=2e5+5;
int blo[N], col[N], par[N], vis[N], typ[N], siz[N], zle[N];
vector<int> co[N];
vector<int> E[N];
int cent;
void color(int v, int p, int c, int n){
col[v]=c;
bool czy=1;
siz[v]=1;
for(int u:E[v]){
if(!blo[u] && u!=p){
color(u, v, c, n);
siz[v]+=siz[u];
if(siz[u]*2>n)czy=0;
}
}
if(siz[v]*2<n)czy=0;
if(czy)cent=v;
}
void dfs(int v){
for(int u:E[v]){
if(u!=par[v] && !blo[u]){
par[u]=v;
dfs(u);
}
}
}
int wsk=1;
int ans=N;
void solve(int v, int id){
par[v]=0;
dfs(v);
vector<int> V;
V.push_back(typ[v]);
vis[typ[v]]=1;
for(int i=0; i<V.size(); i++){
int c=V[i];
for(int v:co[c]){
if(col[v]!=id){
zle[c]=1;
for(int u:V)vis[u]=0;
return;
}
if(par[v] && !vis[typ[par[v]]]){
if(zle[typ[par[v]]]){
for(int u:V)vis[u]=0;
return;
}
vis[typ[par[v]]]=1;
V.push_back(typ[par[v]]);
}
}
}
ans=min(ans, (int)V.size());
for(int u:V)vis[u]=0;
}
void rek(int v, int n){
cent=v;
color(v, 0, wsk++, n);
solve(cent, col[cent]);
blo[cent]=1;
for(int u:E[cent])if(!blo[u])rek(u, siz[u]);
}
mt19937 rng(chrono::high_resolution_clock::now().time_since_epoch().count());
int main(){
ios_base::sync_with_stdio(0);cin.tie(0);
int n, k;
cin>>n>>k;
for(int i=1; i<n; i++){
int u, v;
cin>>u>>v;
E[u].push_back(v);
E[v].push_back(u);
}
for(int i=1; i<=n; i++){
cin>>typ[i];
co[typ[i]].push_back(i);
}
vector<int> kol;
for(int i=1; i<=n; i++)kol.push_back(i);
rek(1, n);
cout<<ans-1<<"\n";
}
Compilation message (stderr)
capital_city.cpp: In function 'void solve(int, int)':
capital_city.cpp:38:16: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
38 | for(int i=0; i<V.size(); i++){
| ~^~~~~~~~~
# | 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... |