[NOI2011]道路修建

树论

一道大水题,直接放代码:

code:

#include<iostream>
#include<cstdio>
#include<queue>
#include<algorithm>
#include<cstring>
#define int long long 
#define half (l+r)>>1
const int maxn=2000006; 
using namespace std;
int head[maxn],cur,d[maxn],hi[maxn];
int qa[maxn],qb[maxn],qc[maxn];
struct hzw
{
	int to,next,v;
}e[maxn];
inline void add(int a,int b,int c)
{
	e[cur].to=b;
	e[cur].next=head[a];
	e[cur].v=c;
	head[a]=cur++;
}
inline void dfs(int s,int fa)
{
	d[s]=1;
	hi[s]=hi[fa]+1;
	for (int i=head[s];i!=-1;i=e[i].next)
	{
		if (e[i].to==fa) continue;
		dfs(e[i].to,s);
		d[s]+=d[e[i].to];
	}
}
inline int abs_(int x,int y)
{
	return x>y?x-y:y-x;
}
int n;
signed main()
{
	memset(head,-1,sizeof(head));
	cin>>n;
	for (int i=1,a,b,c;i<=n-1;++i)
	{
		scanf("%lld%lld%lld",&a,&b,&c);
		add(a,b,c);
		add(b,a,c);
		qa[i]=a;
		qb[i]=b;
		qc[i]=c;
	}
	dfs(1,1);
	int ans=0;
	for (int i=1;i<=n-1;++i)
	{
		int x=qa[i],y=qb[i],z=qc[i];
		int tmp=hi[x]>hi[y]?d[x]:d[y];
		ans=ans+z*abs_(tmp,n-tmp);
	}
	cout<<ans;
	return 0;
}

收获:注意马力,15分钟才切,太菜了。

posted @ 2018-09-16 16:11  Splitor  阅读(168)  评论(0编辑  收藏  举报