제출 #1146923

#제출 시각아이디문제언어결과실행 시간메모리
1146923KK_1729수도 (JOI20_capital_city)C++20
0 / 100
180 ms37136 KiB
#include <bits/stdc++.h> using namespace std; #define int long long #define FOR(i,a,b) for (int i = (a); i < (b); ++i) #define pb push_back #define all(a) a.begin(), a.end() // #define endl "\n" void printVector(vector<int> a){ for (auto x: a) cout << x << " "; cout << endl; } int min(int x, int y){ if (x < y) return x; else return y; } vector<vector<int>> graph; vector<int> subtree; vector<int> vis; int ans = 200000; vector<int> overall; int dp(int x, int p = -1){ if (vis[x]) return 0; subtree[x] = 1; for (auto item: graph[x]){ if (item == p) continue; subtree[x] += dp(item, x); } return subtree[x]; } int find_centroid(int x, int p, int n){ for (auto node: graph[x]){ if (node == p) continue; if (!vis[node] && subtree[node]*2 > n) return find_centroid(node, x, n); } return x; } vector<int> par; vector<vector<int>> o; vector<int> done; vector<int> b; vector<int> col; void setup(int x, int p = -1){ o[col[x]].pb(x); b.pb(x); for (auto node: graph[x]){ if (node == p) continue; par[node] = x; setup(node, x); } } void init_centroid(int x = 1, int p = -1){ // cout << x << endl; dp(x); int c = find_centroid(x, -1, subtree[x]); // cout << c << endl; setup(c); stack<int> s; s.push(col[c]); vector<int> e; while (!s.empty()){ int current = s.top(); s.pop(); if (done[current]) continue; e.pb(current); for (auto item: o[current]){ if (col[par[item]] != col[item] && !done[col[par[item]]]) s.push(col[par[item]]); } done[current] = 1; } bool can = true; for (auto item: e){ if (o[item].size() != overall[item]) can = false; } if (can){ // cout << c << e.size() << endl; ans = min(ans, ((int)e.size()-1)); } for (auto item: e){ o[item].clear(); done[item] = 0; } for (auto item: b) par[item] = -1; b.clear(); vis[c] = 1; for (auto node: graph[c]){ if (!vis[node]) init_centroid(node, c); } } void solve(){ int n, k; cin >> n >> k; graph.resize(n+1); par.resize(n+1); o.resize(k+1); overall.resize(k+1); done.resize(k+1); subtree.resize(n+1); vis.resize(n+1); col.resize(n+1); FOR(i,0,n-1){ int a, b; cin >> a >> b; graph[a].pb(b); graph[b].pb(a); } FOR(i,1,n+1){ cin >> col[i]; overall[col[i]]++; } init_centroid(); cout << ans << endl; } int32_t main(){ ios::sync_with_stdio(false);cin.tie(nullptr); int t = 1; // cin >> t; while (t--) solve(); }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...