Submission #1046171

#TimeUsernameProblemLanguageResultExecution timeMemory
1046171vladiliusMergers (JOI19_mergers)C++17
100 / 100
503 ms132256 KiB
#include <bits/stdc++.h> using namespace std; using ll = long long; using pii = pair<int, int>; #define pb push_back #define ff first #define ss second #define ins insert int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n, k; cin>>n>>k; vector<int> g[n + 1]; for (int i = 1; i < n; i++){ int x, y; cin>>x>>y; g[x].pb(y); g[y].pb(x); } vector<int> s(n + 1), all[k + 1]; for (int i = 1; i <= n; i++){ cin>>s[i]; all[s[i]].pb(i); } vector<int> sz(n + 1), h(n + 1), d(n + 1), p(n + 1); function<void(int, int)> fill = [&](int v, int pr){ p[v] = pr; d[v] = d[pr] + 1; sz[v] = 1; for (int i: g[v]){ if (i == pr) continue; fill(i, v); if (sz[i] > sz[h[v]]){ h[v] = i; } sz[v] += sz[i]; } }; fill(1, 0); vector<int> head(n + 1), pos(n + 1); int timer = 0; function<void(int, int)> fill_hld = [&](int v, int k){ head[v] = k; pos[v] = ++timer; if (!h[v]) return; fill_hld(h[v], k); for (int i: g[v]){ if (pos[i]) continue; fill_hld(i, i); } }; fill_hld(1, 1); set<int> st; for (int i = 2; i <= n; i++) st.ins(i); vector<int> a(n + 2); auto rem = [&](int l, int r){ a[l]++; a[r + 1]--; }; auto upd = [&](int x, int y){ while (head[x] != head[y]){ if (d[head[x]] > d[head[y]]){ swap(x, y); } rem(pos[head[y]], pos[y]); y = p[head[y]]; } if (d[x] > d[y]) swap(x, y); rem(pos[x] + 1, pos[y]); }; for (int i = 1; i <= k; i++){ for (int j = 0; j + 1 < all[i].size(); j++){ upd(all[i][j], all[i][j + 1]); } } vector<int> inv(n + 1), pr(n + 1); for (int i = 1; i <= n; i++){ inv[pos[i]] = i; pr[i] = pr[i - 1] + a[i]; } vector<bool> ban(n + 1); vector<int> bd; for (int i = 2; i <= n; i++){ if (!pr[i]){ bd.pb(inv[i]); ban[inv[i]] = 1; } } auto f = [&](int x, int y){ return (d[x] > d[y]) ? x : y; }; vector<int> gr(n + 1); timer = 0; function<void(int)> dfs = [&](int v){ gr[v] = timer; for (int i: g[v]){ if (gr[i] || ban[f(i, v)]) continue; dfs(i); } }; for (int i = 1; i <= n; i++){ if (!gr[i]){ timer++; dfs(i); } } if (timer == 1){ cout<<0<<"\n"; return 0; } vector<int> cc(timer + 1); for (int i: bd){ cc[gr[i]]++; cc[gr[p[i]]]++; } int tot = 0; for (int i = 1; i <= timer; i++) tot += (cc[i] == 1); cout<<(tot + 1) / 2<<"\n"; }

Compilation message (stderr)

mergers.cpp: In function 'int main()':
mergers.cpp:80:31: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
   80 |         for (int j = 0; j + 1 < all[i].size(); j++){
      |                         ~~~~~~^~~~~~~~~~~~~~~
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...