城市建设方案(树型DP)

题目大意说明:

一个无向图,每条边的代价是 边长度*边两侧的点数的绝对值。求整个图的代价

解题说明:问题在于怎么求出边两端的点数~

AC代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN=1e6+10;
ll ans=0;
struct edge{
	int v,next,len;
}E[MAXN<<2];
int p[MAXN],eid,n;
void init(){
	memset(p,-1,sizeof(p));
	eid=0;
}
void inst(int u,int v,int w){
	E[eid].v=v;
	E[eid].len=w;
	E[eid].next=p[u];
	p[u]=eid++;
}
ll dfs(int star,int last){
	 ll re=1;
	 for(int i=p[star];i+1;i=E[i].next){
	 	int v=E[i].v;
	 	if(v==last)continue;
	 	ll temp=dfs(v,star);
	 	re+=temp;
	 	ans+=(ll)E[i].len*(ll)abs(n-2*temp);
	 }
	 return re;
}
int main(){
	init();
    scanf("%d",&n);
	for(int i=1;i<n;i++){
		int ip1,ip2,ip3;
		scanf("%d%d%d",&ip1,&ip2,&ip3);
		inst(ip1,ip2,ip3);
		inst(ip2,ip1,ip3);
	}
    dfs(1,0);
	printf("%lld\n",ans);
	return 0;
}
 

猜你喜欢

转载自blog.csdn.net/zxk_hi/article/details/80370182
今日推荐