洛谷P1131 [ZJOI2007]时态同步

题目

贪心

贪心思路是先找到每个节点的到最深处的路径,并找到最大值。然后最后答案要加上该最大值和所有路径权值的差。

#include <bits/stdc++.h>
#define N 600101
#define int long long
using namespace std;
int n, root, cnt, ans, lin[N], siz[N], dp[N], maxn[N];//dp[i]表示i为根的树的所需要的时间
struct edg {
 	int to, nex, len;//len表示的是路径权值,并不只是一条边
}e[N * 3];
inline void add(int f, int t, int l)
{
 	e[++cnt].to = t;
 	e[cnt].len = l;
 	e[cnt].nex = lin[f];
 	lin[f] = cnt;
}
int dfs(int now, int fa)
{
 	for (int i = lin[now]; i; i = e[i].nex)
 	{
 		int to = e[i].to;
 		if (to == fa) continue;
 			dfs(to, now);
 		e[i].len += maxn[to]; 
 		maxn[now] = max(maxn[now], e[i].len);
 	}
 	for (int i = lin[now]; i; i = e[i].nex)
 	{
 		int to = e[i].to;
 		if (to == fa)
		 	continue;
 		ans += maxn[now] - e[i].len;
 	}
}
signed main()
{
 	scanf("%lld%lld", &n, &root);
 	for (int i = 1, a, b, c; i < n; i++)
 		scanf("%lld%lld%lld", &a, &b, &c), add(a, b, c), add(b, a, c);
 	dfs(root, 0);		
 	printf("%lld", ans);
 	return 0;
}
/*
4 1  
1 2 1
1 3 3
3 4 5
*/
posted @ 2019-10-21 15:16  DAGGGGGGGGGGGG  阅读(72)  评论(0)    收藏  举报