P1131 [ZJOI2007]时态同步

十年前的ZJOI真良心,n=1e6还O(n)。

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
#define rep(i,j,k) for(i=j;i<=k;++i)
#define per(i,j,k) for(i=j;i>=k;--i)
#define sqr(x) ((x)*(x))
#define G getchar()
#define LL long long
#define pil pair<int,LL>
#define mkp make_pair
#define X first
#define Y second
#define N 1000005
#define NN 10000000
#define inf 1061109567
#define eps 0.00001
int n,rt,tot,he[N],ne[N<<1],to[N<<1];LL W[N<<1],ans;
int read(){
	int x=0;char ch=G;
	while(ch<48||ch>57)ch=G;
	for(;ch>47&&ch<58;ch=G)x=x*10+ch-48;
	return x;
}
void add(int x,int y,LL z){
	to[++tot]=y;W[tot]=z;ne[tot]=he[x];he[x]=tot;
}
void DFS(int x,int e){
	int i,y,cnt=0;LL Max=0,sum=0;
	for(i=he[x];i;i=ne[i])if(i!=e){
		DFS(y=to[i],i^1);Max=max(Max,W[i]);sum+=W[i];++cnt;
	}
	ans+=Max*cnt-sum;W[e]=W[e^1]=W[e]+Max;
}
int main(){
	int i,x,y;LL z;
	n=read();rt=read();tot=1;
	rep(i,2,n){
		x=read();y=read();z=read();
		add(x,y,z);add(y,x,z);
	}
	DFS(rt,0);printf("%lld\n",ans);
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值