其他分享
首页 > 其他分享> > [ZJOI2007] 时态同步(树形dp)

[ZJOI2007] 时态同步(树形dp)

作者:互联网

传送门

很好的一道树形dp的题目
#include <bits/stdc++.h>
using namespace std;

const int N = 5e5 + 10;
typedef long long ll;
bool vis[N];
ll n, tot, s, head[N], dp[N], maxn[N], ans;

struct Edge{
	ll v, w, next;
}edge[N * 2];

void add(ll u, ll v, ll w){
	edge[tot].v = v;
	edge[tot].w = w;
	edge[tot].next = head[u];
	head[u] = tot ++;
}

void dfs(int now, int fa){
	for(int i = head[now]; i != -1; i = edge[i].next){
		int v = edge[i].v;
		int w = edge[i].w;
		if(v == fa)
			continue;
		dfs(v, now);
		dp[now] = max(dp[now], dp[v] + w);		//找出当前节点的时间最长的一个节点
	}
	for(int i = head[now]; i != -1; i = edge[i].next){
		int v = edge[i].v;
		int w = edge[i].w;
		if(v == fa)
			continue;
		ans += (dp[now] - (dp[v] + w));			//统计差值
	}
}
int main(){
	scanf("%lld%lld", &n, &s);	
	memset(head, -1, sizeof head);
	for(int i = 1; i < n; i ++){
		ll a, b, w;
		scanf("%lld%lld%lld", &a, &b, &w);
		add(a, b, w);
		add(b, a, w);
	}

	dfs(s, 0);

	printf("%lld\n", ans);
	return 0;
} 

标签:时态,head,int,ll,edge,ZJOI2007,now,dp
来源: https://www.cnblogs.com/pureayu/p/14984382.html