Submission #261348

#TimeUsernameProblemLanguageResultExecution timeMemory
261348dooweyCapital City (JOI20_capital_city)C++14
100 / 100
1151 ms42224 KiB
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int, int> pii; #define fi first #define se second #define mp make_pair #define fastIO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); const int N = (int)2e5 + 100; vector<int> Z[N]; vector<int> T[N]; int id[N]; bool ban[N]; int par[N]; int subt[N]; bool now[N]; vector<int> mark; void dfs(int u, int pr){ subt[u] = 1; now[u]=true; mark.push_back(u); for(auto x : T[u]){ if(ban[x] || x == pr) continue; dfs(x, u); subt[u] += subt[x]; } } int up[N]; void dfs1(int u, int pr){ up[u] = pr; for(auto x : T[u]){ if(ban[x] || x == pr) continue; dfs1(x, u); } } int fin(int u){ if(par[u]==u) return u; return par[u]=fin(par[u]); } int res; void decomp(int node){ mark.clear(); dfs(node, -1); int pr = -1; bool is = true; int sz = subt[node]; while(is){ is = false; for(auto x : T[node]){ if(x == pr || ban[x]) continue; if(subt[x] > sz/2){ pr = node; node = x; is = true; break; } } } dfs1(node, node); set<int> has, need; need.insert(id[node]); int cur = 0; bool valid = true; int hh; while(!need.empty() && valid){ auto it = need.begin(); cur ++ ; for(auto x : Z[(*it)]){ if(!now[x]){ // big optimization valid=false; break; } } if(!valid) break; set<int> piss; for(auto x : Z[(*it)]){ hh = x; while(hh != node){ hh=fin(hh); if(!need.count(id[hh]) && !has.count(id[hh]) && !piss.count(id[hh])){ piss.insert(id[hh]); } par[hh] = up[hh]; } } has.insert(*it); need.erase(it); for(auto q : piss) need.insert(q); } if(valid){ res = min(res, cur); } for(auto q : mark){ now[q]=false; par[q]=q; } ban[node]=true; for(auto x : T[node]){ if(!ban[x]) decomp(x); } } int main(){ fastIO; int n, k; cin >> n >> k; for(int i =1; i <= n; i ++ ) par[i]=i; res = k; int u, v; for(int i = 1; i < n; i ++ ){ cin >> u >> v; T[u].push_back(v); T[v].push_back(u); } for(int i = 1; i <= n; i ++ ){ cin >> id[i]; Z[id[i]].push_back(i); } decomp(1); cout << res - 1; return 0; }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...