生活随笔
收集整理的这篇文章主要介绍了
Diversity HDU - 6725
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
给你一棵nn个点的树,对于节点ii,你要给它标上一个[li,ri][li,ri]之间的数,要求所有边两端节点上标的数字的差的绝对值的总和最大。
Input
第一行一个整数T(1≤T≤5)T(1≤T≤5)表示数据组数。对于每组数据格式如下。
第一行一个正整数 n(2≤n≤105)n(2≤n≤105)。
接下来n−1n−1行,每行两个正整数 u,v(1≤u,v≤n)u,v(1≤u,v≤n),表示一条边。
接下来nn行,第ii行两个正整数li,ri(1≤li≤ri≤109)li,ri(1≤li≤ri≤109)。
Output
对于每组数据,一个整数表示答案。
Sample Input
1
5
1 2
2 3
3 4
4 5
1 5
2 7
7 9
5 8
3 4
Sample Output
16
树形dp。首先我们来想,某个节点选定的数一定是那个区间的端点,因为如果是区间中的一个点的话,某个端点一定比它更符合。这样就在两个端点中找一个。
dp[u][0]代表着u这个节点选择左端点的最大值。dp[u][1]代表着u这个节点选择右端点的最大值。
那么状态转移方程是:
dp[u][0]+=max(abs(p[u].x-p[to].x)+dp[to][0],abs(p[u].x-p[to].y)+dp[to][1]);
dp[u][1]+=max(abs(p[u].y-p[to].x)+dp[to][0],abs(p[u].y-p[to].y)+dp[to][1]);
dfs跑一遍之后就能求出来。
代码如下:
#include<bits/stdc++.h>
#define ll long long
using namespace std
;const int maxx
=1e5+100;
struct edge
{int to
,next
;
}e
[maxx
<<1];
struct node
{ll x
,y
;
}p
[maxx
];
int head
[maxx
<<1];
ll dp
[maxx
][2];
int n
,m
,tot
;
inline void init()
{tot
=0;memset(head
,-1,sizeof(head
));
}
inline void add(int u
,int v
)
{e
[tot
].to
=v
,e
[tot
].next
=head
[u
],head
[u
]=tot
++;
}
inline void dfs(int u
,int f
)
{dp
[u
][0]=0;dp
[u
][1]=0;for(int i
=head
[u
];i
!=-1;i
=e
[i
].next
){int to
=e
[i
].to
;if(to
==f
) continue;dfs(to
,u
);dp
[u
][0]+=max(abs(p
[u
].x
-p
[to
].x
)+dp
[to
][0],abs(p
[u
].x
-p
[to
].y
)+dp
[to
][1]);dp
[u
][1]+=max(abs(p
[u
].y
-p
[to
].x
)+dp
[to
][0],abs(p
[u
].y
-p
[to
].y
)+dp
[to
][1]);}
}
int main()
{int t
,x
,y
;scanf("%d",&t
);while(t
--){init();scanf("%d",&n
);for(int i
=1;i
<n
;i
++){scanf("%d%d",&x
,&y
);add(x
,y
);add(y
,x
);}for(int i
=1;i
<=n
;i
++) scanf("%lld%lld",&p
[i
].x
,&p
[i
].y
);dfs(1,0);printf("%lld\n",max(dp
[1][0],dp
[1][1]));}return 0;
}
努力加油a啊,(o)/~
总结
以上是生活随笔为你收集整理的Diversity HDU - 6725的全部内容,希望文章能够帮你解决所遇到的问题。
如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。