码迷,mamicode.com
首页 > 其他好文 > 详细

P2986 [USACO10MAR]伟大的奶牛聚集Great Cow Gat…

时间:2019-10-26 15:26:45      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:str   cow   code   info   struct   highlight   png   +=   i++   

典型树上dp,直接暴力算会超时,小心呀

技术图片

 

 

技术图片

 

 

#include<cstring>
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<vector>
#define maxn 100010
using namespace std;
typedef long long ll;
struct Node {
	int p;
	ll len;
	Node(int a, ll b) :p(a), len(b) {}
};
vector<Node>G[maxn];
void insert(int be, int en,ll len) {
	G[be].push_back(Node(en, len));
}
int n, m;
ll sum = 0;
ll ran[maxn];
ll ans[maxn];
ll list[maxn];
int dfs1(int x, int fa) {
	ll k = 0;
	for (int i = 0; i < G[x].size(); i++) {
		int p = G[x][i].p;
		ll ln = G[x][i].len;
		if (p == fa) continue;
		dfs1(p, x);
		k = ran[p];
		ans[x] += (ans[p] + ran[p] * ln);
		ran[x] += ran[p];
	}
	return 0;
}

int dfs(int x, int fa) {
	for (int i = 0; i < G[x].size(); i++) {
		int p = G[x][i].p;
		ll ln = G[x][i].len;
		if (p == fa) continue;
		ans[p] += ans[x] - (ans[p] + ran[p] * ln) + (sum - ran[p])*ln;
		dfs(p, x);
	}
	return 0;
}
int main() {
	scanf("%d", &n);
	m = n - 1;
	for (int i = 1; i <= n; i++) {
		scanf("%lld", &list[i]);
		sum += list[i];
		ran[i] = list[i];
	}
	int be, en;
	ll len;
	for (int i = 0; i < m; i++) {
		scanf("%d%d%lld", &be, &en, &len);
		insert(be, en, len);
		insert(en, be, len);
	}
	dfs1(1, -1);
	dfs(1, -1);
	ll cns = 10000000000000000;
	for (int i = 1; i <= n; i++) {
		cns = min(cns, ans[i]);
	}
	printf("%lld\n", cns);
	return 0;
}

  

P2986 [USACO10MAR]伟大的奶牛聚集Great Cow Gat…

标签:str   cow   code   info   struct   highlight   png   +=   i++   

原文地址:https://www.cnblogs.com/lesning/p/11743101.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!