HDU 6201 transaction transaction transaction

Kelukin is a businessman. Every day, he travels around cities to do some business. On August 17th, in memory of a great man, citizens will read a book named "the Man Who Changed China". Of course, Kelukin wouldn't miss this chance to make money, but he doesn't have this book. So he has to choose two city to buy and sell. 
As we know, the price of this book was different in each city. It is aiai yuanyuan in iittcity. Kelukin will take taxi, whose price is 11yuanyuan per km and this fare cannot be ignored. 
There are n1n−1 roads connecting nn cities. Kelukin can choose any city to start his travel. He want to know the maximum money he can get. 

Input

The first line contains an integer TT (1T101≤T≤10) , the number of test cases. 
For each test case: 
first line contains an integer nn (2n1000002≤n≤100000) means the number of cities; 
second line contains nn numbers, the iithth number means the prices in iithth city; (1Price10000)(1≤Price≤10000) 
then follows n1n−1 lines, each contains three numbers xx, yy and zz which means there exists a road between xx and yy, the distance is zzkmkm (1z1000)(1≤z≤1000). 
Output

For each test case, output a single number in a line: the maximum money he can get. 

Sample Input

1  
4  
10 40 15 30  
1 2 30
1 3 2
3 4 10

Sample Output

8
题解:树形DP。这是让求从任意一点买书,然后到任意一点卖书,每条路都会耗费一定的费用,让求最多可挣多少钱。
我们可以吧任意一个节点当成根节点,然后树形DP,(就是DFS遍历),dp[x][1]代表以x为根节点的子树中中卖书
的最大值,dp[x][0]表示以x为根节点的子树中买书的最小费用。然后求dp[1~n][1]-dp[1~n][0]的最大值即可。

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 typedef long long LL;
 4 const int INF=0x3f3f3f3f;
 5 const int maxn=1e5+10;
 6 int T,n,w[maxn],x,y,z,dp[maxn][2],Max,vis[maxn];
 7 struct Edge{
 8     int v,w;
 9     Edge(int vv,int ww):v(vv),w(ww) { }
10 };
11 vector<Edge> vec[maxn]; 
12 void addedge(int u,int v,int w)
13 {
14     vec[u].push_back(Edge(v,w));
15 }
16 
17 void dfs(int s)
18 {
19     vis[s]=1;
20     for(int i=0;i<vec[s].size();i++) if(!vis[vec[s][i].v]) dfs(vec[s][i].v);
21     for(int i=0;i<vec[s].size();i++)
22     {
23         dp[s][0]=min(dp[s][0],dp[vec[s][i].v][0]+vec[s][i].w);
24         dp[s][1]=max(dp[s][1],dp[vec[s][i].v][1]-vec[s][i].w);
25     }
26 }
27 
28 int main()
29 {
30     scanf("%d",&T);
31     while(T--)
32     {
33         memset(dp,0,sizeof dp);
34         memset(vis,0,sizeof vis);
35         scanf("%d",&n); 
36         for(int i=1;i<=n;i++) vec[i].clear();
37         for(int i=1;i<=n;i++) scanf("%d",w+i),dp[i][0]=dp[i][1]=w[i];
38         for(int i=1;i<n;i++)
39         {
40             scanf("%d%d%d",&x,&y,&z);
41             addedge(x,y,z); addedge(y,x,z);
42         }
43         dfs(1); Max=0;
44         for(int i=1;i<=n;i++) Max=max(Max,dp[i][1]-dp[i][0]);
45         printf("%d
",Max);
46     }
47     
48     return 0;
49  } 
View Code
原文地址:https://www.cnblogs.com/csushl/p/9415991.html