cf 722 C. Parsa‘s Humongous Tree(树形dp)

C. Parsa’s Humongous Tree
Parsa has a humongous tree on n vertices.

On each vertex v he has written two integers lv and rv.

To make Parsa’s tree look even more majestic, Nima wants to assign a number av (lv≤av≤rv) to each vertex v such that the beauty of Parsa’s tree is maximized.

Nima’s sense of the beauty is rather bizarre. He defines the beauty of the tree as the sum of |au−av| over all edges (u,v) of the tree.

Since Parsa’s tree is too large, Nima can’t maximize its beauty on his own. Your task is to find the maximum possible beauty for Parsa’s tree.

Input
The first line contains an integer t (1≤t≤250) — the number of test cases. The description of the test cases follows.

The first line of each test case contains a single integer n (2≤n≤105) — the number of vertices in Parsa’s tree.

The i-th of the following n lines contains two integers li and ri (1≤li≤ri≤109).

Each of the next n−1 lines contains two integers u and v (1≤u,v≤n,u≠v) meaning that there is an edge between the vertices u and v in Parsa’s tree.

It is guaranteed that the given graph is a tree.

It is guaranteed that the sum of n over all test cases doesn’t exceed 2⋅105.

Output
For each test case print the maximum possible beauty for Parsa’s tree.

Example
inputCopy
3
2
1 6
3 8
1 2
3
1 3
4 6
7 9
1 2
2 3
6
3 14
12 20
12 19
2 12
10 17
3 17
3 2
6 5
1 5
2 6
4 6
outputCopy
7
8
62
大意:每个结点有一个范围的值,每条边的权值为两结点差的绝对值,整棵树的总价值为全部边的权值之和,求整棵树的最大总价值

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll mod=1e9+7;
#define maxx 100010
ll a[maxx][2],l[maxx],r[maxx];
vector<int>e[maxx];
void dfs(int child,int fa){
	for(auto i:e[child]){
		if(i==fa)continue;//防止往回走 
		dfs(i,child);
		a[child][0]+=max(a[i][0]+abs(l[child]-l[i]),a[i][1]+abs(l[child]-r[i]));//用最小值计算 
		a[child][1]+=max(a[i][0]+abs(r[child]-l[i]),a[i][1]+abs(r[child]-r[i]));//用最大值计算
	}
}
int main()
{
	int t;
	scanf("%d",&t);
	while(t--){
		int n;
		scanf("%d",&n);
		memset(a,0,sizeof(a));
		for(int i=1;i<=n;i++) scanf("%lld%lld",&l[i],&r[i]),e[i].clear();
		for(int i=1;i<n;i++){
			int a,b;
			scanf("%d%d",&a,&b);
			//放入边,两结点之间是双向关系 
			e[a].push_back(b);
			e[b].push_back(a);
		}
		dfs(1,1);
		printf("%lld\n",max(a[1][0],a[1][1]));//比较两种方案哪个更好 
	}
	return 0;
}







  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值