luogu P2052 [NOI2011]道路修建

题面传送门
按照题意模拟即可,把每个点的子树节点数遍历出来,然后与 n − f x n-f_x nfx取绝对值即可。
代码实现:

#include<cstdio>
#include<cstring>
#define abs(x)((x)>0?(x):-(x))
using namespace std;
int n,m,k,x,y,z;
long long f[1000039],ans;
struct yyy{int to,w,z;};
struct ljb{
	int head,h[1000039];
	yyy f[2000039];
	inline void add(int x,int y,int z){
		f[++head]=(yyy){y,z,h[x]};
		h[x]=head;
	}
}s;
inline void read(int &x){
	char s=getchar();x=0;
	while(s<'0'||s>'9') s=getchar();
	while(s>='0'&&s<='9') x=(x<<3)+(x<<1)+(s^48),s=getchar();
}
inline void dfs(int x,int last){
	f[x]=1;
	int cur=s.h[x];
	yyy tmp;
	while(cur!=-1){
		tmp=s.f[cur];
		if(tmp.to!=last) dfs(tmp.to,x),f[x]+=f[tmp.to],ans+=abs(f[tmp.to]-(n-f[tmp.to]))*tmp.w;
		cur=tmp.z;
	}
}
int main(){
	memset(s.h,-1,sizeof(s.h));
	register int i;
	read(n);
	for(i=1;i<n;i++)read(x),read(y),read(z),s.add(x,y,z),s.add(y,x,z);
	dfs(1,1);
	printf("%lld\n",ans);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值