bzoj2435: [Noi2011]道路修建 【树形dp】

记录size


dfs 乱搞


有人说貌似是树形dp



#include <cstring>
#include <cstdio>
#define LL long long
#define lp(i,j,k) for(int i = j;i <= k;++i)
LL abs (LL a) {
	if(a <= 0)
		return -a;
	return a;
}
int read () {
	int re = 0;
	char c = getchar();
	while(c < '0' || c > '9')
		c = getchar();
	while(c <= '9' && c >= '0') {
		re = re * 10 + c - '0';
		c = getchar();
	}
	return re;
}
int n,U,V,W;
LL ans;
struct edge {
	int v,next,w;
}e[2000010];
int cnt,head[1000010],depth[1000010],sz[1000010];
void adde (int u,int v,int w) {
	e[++cnt].v = v;
	e[cnt].w = w;
	e[cnt].next = head[u];
	head[u] = cnt;
	e[++cnt].v = u;
	e[cnt].w = w;
	e[cnt].next = head[v];
	head[v] = cnt;
}
void dfs (int u,int I) {
	for(int i = head[u];i != -1;i = e[i].next) {
		int v = e[i].v;
		if(!depth[v]) {
			depth[v] = depth[u] + 1;
			dfs(v,i);
			sz[u] += sz[v];
		}
	}
	sz[u]++;
	ans += (LL)e[I].w * abs((LL)(n - sz[u] - sz[u]));
}
int main () {
	memset(head,-1,sizeof head);
	n = read();
	lp(i,1,n - 1) {
		U = read();
		V = read();
		W = read();
		adde(U,V,W);
	}
	depth[1] = 1;
	dfs(1,0);
	printf("%lld\n",ans);
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值