Submission #1039545

#TimeUsernameProblemLanguageResultExecution timeMemory
1039545DucNguyen2007Mergers (JOI19_mergers)C++14
100 / 100
890 ms169748 KiB
#include<bits/stdc++.h> using namespace std; #define ll long long #define ld long double #define pii pair<int,int> #define pll pair<ll,ll> #define fi first #define se second const int maxN=5e5+5,LG=__lg(maxN)+5; const ll inf=2e18; int n,k,a[maxN+1],num[maxN+1],timer=0,h[maxN+1],up[maxN+1][LG+1],f[maxN+1]; vector<int> adj[maxN+1],vec[maxN+1],nadj[maxN+1]; void dfs(int u) { num[u]=++timer; for(auto v:adj[u]) { if(v==up[u][0]) { continue; } up[v][0]=u; h[v]=h[u]+1; for(int j=1;j<=LG;j++) { up[v][j]=up[up[v][j-1]][j-1]; } dfs(v); } } int lca(int u,int v) { if(h[u]<h[v]) { swap(u,v); } for(int j=LG;j>=0;j--) { if(h[up[u][j]]>=h[v]) { u=up[u][j]; } } if(u==v) { return u; } for(int j=LG;j>=0;j--) { if(up[u][j]!=up[v][j]) { u=up[u][j]; v=up[v][j]; } } return up[u][0]; } void dfs1(int u) { for(auto v:adj[u]) { if(v!=up[u][0]) { dfs1(v); f[u]+=f[v]; } } } void dfs2(int u,int p) { for(auto v:adj[u]) { if(v!=up[u][0]) { int nv=p; if(!f[v]) { //cout<<u<<" "<<v<<'\n'; nadj[v].push_back(p); nadj[p].push_back(v); nv=v; } dfs2(v,nv); } } } int main() { //freopen("","r",stdin); //freopen("","w",stdout); ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin>>n>>k; for(int i=1;i<n;i++) { int u,v; cin>>u>>v; adj[u].push_back(v); adj[v].push_back(u); } h[1]=1; dfs(1); for(int i=1;i<=n;i++) { cin>>a[i]; vec[a[i]].push_back(i); } for(int i=1;i<=k;i++) { sort(vec[i].begin(),vec[i].end(),[&](int x,int y) { return num[x]<num[y]; }); int len=vec[i].size(); if(len==1) { continue; } for(int j=0;j<len;j++) { int u=vec[i][j],v=vec[i][(j+1)%len]; f[u]++; f[lca(u,v)]--; } } dfs1(1); dfs2(1,1); int cnt=0; for(int i=1;i<=n;i++) { cnt+=(nadj[i].size()==1); } cout<<(cnt+1)/2; }
#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...