Submission #1114238

#TimeUsernameProblemLanguageResultExecution timeMemory
1114238Dan4LifeMergers (JOI19_mergers)C++17
34 / 100
3100 ms52976 KiB
#include <bits/stdc++.h> using namespace std; #define pb push_back #define sz(a) (int)a.size() #define all(a) begin(a),end(a) using ar2 = array<int,2>; const int N = (int)5e5+10; int n, k; int p[N], sz[N]; int a[N], tot[N], cnt[N], deg[N]; vector<int> v[N], adj[N]; int findSet(int i){return i==p[i]?i:p[i]=findSet(p[i]);} void unionSet(int i, int j){ int x = findSet(i), y = findSet(j); if(x==y) return; if(sz[x]<sz[y])swap(x,y); p[y] = x, sz[x]+=sz[y]; } void dfs(int s, int p){ v[s].pb(a[s]); for(auto u : adj[s]){ if(u==p) continue; dfs(u,s); if(sz(v[s]) < sz(v[u])) v[s].swap(v[u]); for(auto w : v[u]) v[s].pb(w); v[u].clear();v[u].shrink_to_fit(); } int ok = 1; for(auto u : v[s]) cnt[u]++; for(auto u : v[s]){ ok&=(cnt[u]==tot[u]); if(!ok) break; } for(auto u : v[s]) cnt[u]--; if(p and !ok) unionSet(s,p); } int32_t main(){ ios_base::sync_with_stdio(false); cin.tie(0); cin >> n >> k; for(int i = 1; i <= n; i++) p[i]=i,sz[i]=1; for(int i = 1; i < n; i++){ int a, b; cin >> a >> b; adj[a].pb(b); adj[b].pb(a); } for(int i = 1; i <= n; i++) cin >> a[i], tot[a[i]]++; dfs(1,0); for(int i = 1; i <= n; i++){ int x = findSet(i); for(int j : adj[i]) deg[x]+=(x!=findSet(j)); } int cnt = 1; for(int i = 1; i <= n; i++) cnt+=(deg[i]==1); cout << cnt/2 << "\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...