Submission #1050856

#TimeUsernameProblemLanguageResultExecution timeMemory
1050856Jarif_RahmanMergers (JOI19_mergers)C++17
100 / 100
470 ms74944 KiB
#include <bits/stdc++.h> #define pb push_back #define f first #define sc second using namespace std; typedef long long int ll; typedef string str; int n, k; vector<vector<int>> tree; vector<int> sz; vector<int> state, scnt; vector<int> cnt; int bsc = 0; vector<bool> sep; int sep_cnt = 0; void pre_dfs(int nd, int ss){ for(int x: tree[nd]) if(x != ss) pre_dfs(x, nd), sz[nd]+=sz[x]; } void add(int nd, int ss){ cnt[state[nd]]++; if(cnt[state[nd]] == 1) bsc++; if(cnt[state[nd]] == scnt[state[nd]]) bsc--; for(int x: tree[nd]) if(x != ss) add(x, nd); } void remove(int nd, int ss){ cnt[state[nd]]--; if(cnt[state[nd]] == scnt[state[nd]]-1) bsc++; if(cnt[state[nd]] == 0) bsc--; for(int x: tree[nd]) if(x != ss) remove(x, nd); } void dfs(int nd, int ss, bool keep){ int bigchild = -1, bigchild_size = -1; for(int x: tree[nd]) if(x != ss && sz[x] > bigchild_size) bigchild_size = sz[x], bigchild = x; for(int x: tree[nd]) if(x != ss && x != bigchild) dfs(x, nd, 0); if(bigchild != -1) dfs(bigchild, nd, 1); cnt[state[nd]]++; if(cnt[state[nd]] == 1) bsc++; if(cnt[state[nd]] == scnt[state[nd]]) bsc--; for(int x: tree[nd]) if(x != ss && x != bigchild) add(x, nd); if(ss != -1 && bsc == 0) sep[nd] = 1; if(sep[nd]) sep_cnt++; if(keep) return; cnt[state[nd]]--; if(cnt[state[nd]] == scnt[state[nd]]-1) bsc++; if(cnt[state[nd]] == 0) bsc--; for(int x: tree[nd]) if(x != ss) remove(x, nd); } int ans = 0; bool exta = 0; int dfs2(int nd, int ss, int sep_cnt_ = 0){ int c = 0; for(int x: tree[nd]) if(x != ss) c+=dfs2(x, nd, sep_cnt_+sep[nd]); if(ss == -1) return 0; if(!sep[nd]) return c; c++; if(c == 1) ans++; else if(c+sep_cnt_ == sep_cnt) exta = 1; return c; } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cin >> n >> k; tree.resize(n); sz.resize(n, 1); state.resize(n); scnt.resize(k, 0); cnt.resize(k, 0); sep.resize(n, 0); for(int i = 0; i < n-1; i++){ int a, b; cin >> a >> b; a--, b--; tree[a].push_back(b); tree[b].push_back(a); } for(int i = 0; i < n; i++){ cin >> state[i]; state[i]--; scnt[state[i]]++; } pre_dfs(0, -1); dfs(0, -1, 1); dfs2(0, -1); ans+=exta; ans++; ans/=2; cout << ans << "\n"; }
#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...