Submission #564816

#TimeUsernameProblemLanguageResultExecution timeMemory
564816uroskMergers (JOI19_mergers)C++14
100 / 100
2796 ms250316 KiB
// __builtin_popcount(x) // __builtin_popcountll(x) #define here cerr<<"===========================================\n" #include <bits/stdc++.h> #define ld double #define ll long long #define ull unsigned long long #define llinf 100000000000000000LL // 10^17 #define iinf 2000000000 // 2*10^9 #define pb push_back #define popb pop_back #define fi first #define sc second #define endl '\n' #define pii pair<int,int> #define pll pair<ll,ll> #define pld pair<ld,ld> #define sz(a) int(a.size()) #define all(a) a.begin(),a.end() #define ceri(a,l,r) {for(ll i_ = l;i_<=r;i_++) cerr<<a[i_]<< " ";cerr<<endl;} using namespace std; #define maxn 500005 ll n,k; vector<ll> g[maxn]; vector<ll> v; ll a[maxn]; ll in[maxn]; ll out[maxn]; ll dp[maxn][3]; ll b[maxn][3]; ll it = 1; void dfs(ll u,ll par){ in[u] = it++; for(ll s : g[u]){ if(s==par) continue; dfs(s,u); } out[u] = it-1; } bool intree(ll x,ll i){ return x>=in[i]&&out[i]>=x; } bool bio[maxn]; ll ans = 0; set<ll> rg[maxn]; ll dsu[maxn]; ll root(ll x){ while(x!=dsu[x]){ dsu[x] = dsu[dsu[x]]; x = dsu[x]; } return x; } void upd(ll x,ll y){ x = root(x); y = root(y); dsu[x] = y; } map<pll,bool> mp; void dfs2(ll u,ll par){ dp[u][1] = b[a[u]][1]; dp[u][2] = b[a[u]][2]; for(ll s : g[u]){ if(s==par) continue; dfs2(s,u); dp[u][1] = min(dp[u][1],dp[s][1]); dp[u][2] = max(dp[u][2],dp[s][2]); bio[u]|=bio[s]; } bool da = 0; if(u!=par){ if(intree(dp[u][1],u)&&intree(dp[u][2],u)) da = 1; } //cerr<<"u: "<<u<<" "<<in[u]<< " "<<out[u]<<" "<<dp[u][1]<< " "<<dp[u][2]<<endl; if(da){ mp[{u,par}] = mp[{par,u}] = 1; } } bool vis[maxn]; void dfs3(ll u,ll par){ vis[u] = 1; for(ll s : g[u]){ if(s==par) continue; if(mp[{s,u}]) continue; upd(u,s); dfs3(s,u); } } vector<pll> e; int main(){ ios_base::sync_with_stdio(false);cerr.tie(0);cout.tie(0);cin.tie(0); cin >> n >> k; iota(dsu+1,dsu+n+1,1); for(ll i = 1;i<=n-1;i++){ ll x,y; cin >> x >> y; g[x].pb(y); g[y].pb(x); e.pb({x,y}); } for(ll i = 1;i<=n;i++) cin >> a[i]; dfs(1,1); for(ll i = 1;i<=k;i++){ b[i][1] = llinf; b[i][2] = 0; } for(ll i = 1;i<=n;i++){ ll col = a[i]; b[col][1] = min(b[col][1],in[i]); b[col][2] = max(b[col][2],in[i]); } dfs2(1,1); for(ll i = 1;i<=n;i++){ if(vis[i]) continue; dfs3(i,i); } for(pll p : e){ ll x = p.fi; ll y = p.sc; x = root(x); y = root(y); if(x==y) continue; rg[x].insert(y); rg[y].insert(x); } for(ll i = 1;i<=n;i++) if(sz(rg[i])==1) ans++; ans = (ans+1)/2; cout<<ans<<endl; return 0; } /* 5 4 1 2 2 3 3 4 3 5 1 2 1 3 4 5 4 1 2 2 3 3 4 4 5 1 2 3 4 1 5 5 1 2 2 3 3 4 4 5 1 2 3 4 5 */
#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...