1009F - Dominant Indices - CodeForces Solution


data structures dsu trees *2300

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
using namespace std;
const int MAXN=1e6+1;
vector <int> f[MAXN],G[MAXN];
int len[MAXN],lson[MAXN],ans[MAXN];
/*f[i][j]	->	# subtree(i), dist = len[i]-j*/
inline void dfs(int p,int fa)	{
	for(int v:G[p])	{
		if(v==fa) continue;
		dfs(v,p);
		len[p]=max(len[p],len[v]+1);
		if(len[lson[p]]<=len[v]) lson[p]=v;
	}
}
inline void solve(int p,int fa)	{
	if(!lson[p])	{
		f[p].push_back(1);
		ans[p]=0;
		return ;
	}
	solve(lson[p],p);
	swap(f[lson[p]],f[p]);
	ans[p]=ans[lson[p]];
	f[p].push_back(1);
	if(f[p][ans[p]]==1) ans[p]=len[p];
	for(int v:G[p])	{
		if(v==fa||v==lson[p]) continue;
		solve(v,p);
		for(int x=0;x<=len[v];++x)	{
			int d=len[p]-(len[v]-x+1);
			f[p][d]+=f[v][x];
			if(f[p][d]>f[p][ans[p]]||(f[p][d]==f[p][ans[p]]&&d>ans[p])) ans[p]=d;
		}
	}
}
signed main()	{
	int n;
	scanf("%d",&n);
	for(int i=1;i<n;++i)	{
		int u,v;
		scanf("%d%d",&u,&v);
		G[u].push_back(v);
		G[v].push_back(u);
	}
	dfs(1,0);
	solve(1,0);
	for(int i=1;i<=n;++i) printf("%d\n",len[i]-ans[i]);
	return 0;
}//9686451989973131033


Comments

Submit
0 Comments
More Questions

1382A - Common Subsequence
1512D - Corrupted Array
667B - Coat of Anticubism
284B - Cows and Poker Game
1666D - Deletive Editing
1433D - Districts Connection
2B - The least round way
1324A - Yet Another Tetris Problem
246B - Increase and Decrease
22E - Scheme
1566A - Median Maximization
1278A - Shuffle Hashing
1666F - Fancy Stack
1354A - Alarm Clock
1543B - Customising the Track
1337A - Ichihime and Triangle
1366A - Shovels and Swords
919A - Supermarket
630C - Lucky Numbers
1208B - Uniqueness
1384A - Common Prefixes
371A - K-Periodic Array
1542A - Odd Set
1567B - MEXor Mixup
669A - Little Artem and Presents
691B - s-palindrome
851A - Arpa and a research in Mexican wave
811A - Vladik and Courtesy
1006B - Polycarp's Practice
1422A - Fence