Bzoj 2435: [Noi2011]道路修建 (dfs)

Bzoj 2435: [Noi2011]道路修建

大水题,会dfs即可.
记录一下size,n - size为另一部分的点..
Bzoj 会爆栈(真坑).
ans记得开longlong,不然只有10分.

#include <iostream>
#include <cstdio>
const int maxN = 1000000 + 7;

int size[maxN],n; // f[i]表示以i为根的子树大小. len * abs (n - 2 * f[i])

long long ans;

struct Node {
	int v,nex,w;
}Map[maxN << 1];

int head[maxN],num;

inline int abs(int a) {return a >= 0 ? a : -a;}

void add_Node(int u,int v,int w) {
	Map[++ num] = (Node) {v,head[u],w};
	head[u] = num;
	return ;
}

inline int read() {
	int x = 0,f = 1;char c = getchar();
	while(c < '0' || c > '9') {if(c == '-')f = -1;c = getchar();}
	while(c >= '0' && c <= '9') {x = x * 10 + c - '0';c = getchar();}
	return x * f;
}

void dfs_1(int now,int fa) {
	size[now] = 1;
	for(int i = head[now];i;i = Map[i].nex) {
		int v = Map[i].v,w = Map[i].w;
		if(v != fa) {
			dfs_1(v,now);
			size[now] += size[v];
			ans += (long long)w * abs(n - 2 * size[v]);
		}
	}
}

int main() {
	n = read();
	for(int i = 1,u,v,w;i < n;++ i) {
		u = read();v = read();w = read();
		add_Node(u,v,w);
		add_Node(v,u,w);
	}
	dfs_1(n,n);
	printf("%lld", ans);
	return 0;
}
posted @ 2018-10-09 14:50  Rlif  阅读(107)  评论(0编辑  收藏  举报