「杂题乱刷」AT_abc220_f

链接

板题。

三个定义:

\(dp_i\) 表示以 \(i\) 为根节点时,其子节点深度的和;

\(siz_i\) 表示以 \(i\) 为根节点时,其子树的大小;

\(dep_i\) 表示以 \(1\) 为根节点时,所有节点的深度。

参考代码:

点击查看代码
/*
Tips:
你数组开小了吗?
你MLE了吗?
你觉得是贪心,是不是该想想dp?
一个小时没调出来,是不是该考虑换题?
*/
#include<bits/stdc++.h>
using namespace std;
#define map unordered_map
#define forl(i,a,b) for(register long long i=a;i<=b;i++)
#define forr(i,a,b) for(register long long i=a;i>=b;i--)
#define forll(i,a,b,c) for(register long long i=a;i<=b;i+=c)
#define forrr(i,a,b,c) for(register long long i=a;i>=b;i-=c)
#define lc(x) x<<1
#define rc(x) x<<1|1
#define mid ((l+r)>>1)
#define cin(x) scanf("%lld",&x)
#define cout(x) printf("%lld",x)
#define lowbit(x) x&-x
#define pb push_back
#define pf push_front
#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
#define endl '\n'
#define QwQ return 0;
#define ll long long
#define ull unsigned long long
#define lcm(x,y) x/__gcd(x,y)*y
#define Sum(x,y) 1ll*(x+y)*(y-x+1)/2
ll t;
ll n,u,v;
vector<ll>G[200010];
ll dp[200010],siz[200010],dep[200010];
void dfs1(ll x,ll last)
{
	siz[x]=1;
	forl(i,0,(ll)G[x].size()-1)
		if(G[x][i]!=last)
		{
			dep[G[x][i]]=dep[x]+1;
			dfs1(G[x][i],x);
			siz[x]+=siz[G[x][i]];
		}
}
void dfs2(ll x,ll last)
{
	forl(i,0,(ll)G[x].size()-1)
		if(G[x][i]!=last)
		{
			dp[G[x][i]]=dp[x]+n-siz[G[x][i]]*2;
			dfs2(G[x][i],x);	
		}
}
void solve()
{
	cin>>n;
	forl(i,1,n-1)
		cin>>u>>v,G[u].pb(v),G[v].pb(u);
	dfs1(1,0);
	forl(i,1,n)
		dp[1]+=dep[i];
	dfs2(1,0);
	forl(i,1,n)
		cout<<dp[i]<<endl;
}
int main()
{
	IOS;
	t=1;
	//cin>>t;
	while(t--)
		solve();
    /******************/
	/*while(L<q[i].l) */
	/*    del(a[L++]);*/
	/*while(L>q[i].l) */
	/*    add(a[--L]);*/
	/*while(R<q[i].r) */
	/*	  add(a[++R]);*/
	/*while(R>q[i].r) */
	/*    del(a[R--]);*/
    /******************/
	QwQ;
}
posted @ 2024-04-26 19:09  wangmarui  阅读(3)  评论(0编辑  收藏  举报