【bzoj2435】 NOI2011 道路修建 水题

其实不能说什么了,貌似你会dfs这道题就能A,当然考场上要写bfs。。。

直接放代码了。。。


#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include<algorithm>
#define maxn 1000010

using namespace std;

int n,m,num;
long long ans;
int next[2*maxn],to[2*maxn],head[maxn];
long long len[2*maxn];
int size[maxn];

void addedge(int x,int y,int z)
{
	num++;to[num]=y;len[num]=z;next[num]=head[x];head[x]=num;
}

void dfs(int x,int fa)
{
	size[x]=1;
	for (int p=head[x];p;p=next[p])
	  if (to[p]!=fa)
	  {
	  	dfs(to[p],x);
	  	size[x]+=size[to[p]];
	  	ans+=(long long)len[p]*abs(n-size[to[p]]-size[to[p]]);
	  }
}

int main()
{
	scanf("%d",&n);
	for (int i=1;i<n;i++)
	{
		int x,y,z;
		scanf("%d%d%d",&x,&y,&z);
		addedge(x,y,z);
		addedge(y,x,z);
	}
	dfs(1,0);
	printf("%lld\n",ans);
	return 0;
}
    原文作者:道路修建问题
    原文地址: https://blog.csdn.net/u012288458/article/details/46943529
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞