# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
223173 | arnold518 | Capital City (JOI20_capital_city) | C++14 | 1053 ms | 38116 KiB |
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;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const int MAXN = 2e5;
int N, K, C[MAXN+10], ans=987654321, num[MAXN+10];
vector<int> adj[MAXN+10];
int sz[MAXN+10], del[MAXN+10];
void getsz(int now, int bef)
{
sz[now]=1;
for(int nxt : adj[now])
{
if(nxt==bef) continue;
if(del[nxt]) continue;
getsz(nxt, now);
sz[now]+=sz[nxt];
}
}
int getcen(int now, int bef, int S)
{
for(int nxt : adj[now])
{
if(nxt==bef) continue;
if(del[nxt]) continue;
if(sz[nxt]>S/2) return getcen(nxt, now, S);
}
return now;
}
int par[MAXN+10], vis[MAXN+10], cvis[MAXN+10];
vector<int> V[MAXN+10];
vector<pii> V2;
void dfs(int now, int bef)
{
par[now]=bef; vis[now]=0; cvis[C[now]]=0;
V[C[now]].push_back(now);
V2.push_back({now, C[now]});
for(int nxt : adj[now])
{
if(nxt==bef) continue;
if(del[nxt]) continue;
dfs(nxt, now);
}
}
void decomp(int now)
{
getsz(now, now);
now=getcen(now, now, sz[now]);
del[now]=true;
dfs(now, now);
queue<int> Q;
Q.push(C[now]);
cvis[C[now]]=true;
int cnt=0;
//printf("CENTROID %d\n", now);
while(!Q.empty())
{
int col=Q.front(); Q.pop(); cnt++;
for(auto it : V[col])
{
int v=it;
while(!vis[v])
{
//printf("%d\n", v);
vis[v]=true;
if(!cvis[C[v]])
{
cvis[C[v]]=true;
Q.push(C[v]);
}
v=par[v];
}
}
}
bool flag=true;
for(auto it : V2) if(cvis[it.second] && V[it.second].size()!=num[it.second]) flag=false;
if(flag) ans=min(ans, cnt);
for(auto it : V2) V[it.second].clear();
V2.clear();
for(int nxt : adj[now])
{
if(del[nxt]) continue;
decomp(nxt);
}
}
int main()
{
int i, j;
scanf("%d%d", &N, &K);
for(i=1; i<N; i++)
{
int u, v;
scanf("%d%d", &u, &v);
adj[u].push_back(v);
adj[v].push_back(u);
}
for(i=1; i<=N; i++) scanf("%d", &C[i]), num[C[i]]++;
decomp(1);
printf("%d\n", ans-1);
}
Compilation message (stderr)
# | 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... |