1060: [ZJOI2007]时态同步

水的一批
(有点像差分)

#include<bits/stdc++.h>
#define re return
#define ll long long
#define inc(i,l,r) for(int i=l;i<=r;++i)

const int maxn=500005;

char buf[1<<21],*p1,*p2;
inline int gc(){re p1==p2 and(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++;}

template<typename T>inline void rd(T&x)
{
	char c;bool f=0;
	while((c=gc())<'0'||c>'9')if(c=='-')f=1;
	x=c^48;
	while((c=gc())>='0'&&c<='9')x=x*10+(c^48);
}

using namespace std;
ll n,k,s,dp[maxn],same[maxn],head[maxn];

struct node
{
	int val,to,nt;
}e[maxn<<1];
void add(int x,int y,int w)
{
	e[++k].to=y;e[k].val=w;e[k].nt=head[x];head[x]=k;
	e[++k].to=x;e[k].val=w;e[k].nt=head[y];head[y]=k;
}

void dfs(int x,int pre)
{
	for(int i=head[x];i;i=e[i].nt)
	{
		int v=e[i].to,w=e[i].val;
		if(v==pre)continue;
		dfs(v,x);
		same[x]=max(same[v]+w,same[x]);
		dp[x]+=dp[v];
	}
	for(int i=head[x];i;i=e[i].nt)
		if(e[i].to!=pre)dp[x]+=same[x]-same[e[i].to]-e[i].val;
	re;	
}


int main()
{
//	freopen("in.txt","r",stdin);
	int x,y,z;
	rd(n);rd(s);
	inc(i,2,n){
		rd(x),rd(y),rd(z);
		add(x,y,z);
	}
	
	dfs(s,0);
	
	printf("%lld",dp[s]);
	re 0;
} 

猜你喜欢

转载自blog.csdn.net/weixin_44575377/article/details/89839455