hdu 6201 transaction transaction transaction

来源:互联网 发布:js基本数据类型有哪些 编辑:程序博客网 时间:2024/06/02 06:07
Problem Description
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 ai yuan in it city. Kelukin will take taxi, whose price is 1yuan per km and this fare cannot be ignored.
There are n−1 roads connecting n 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 T (1≤T≤10) , the number of test cases.
For each test case:
first line contains an integer n (2≤n≤100000) means the number of cities;
second line contains n numbers, the ith number means the prices in ith city; (1≤Price≤10000)
then follows n−1 lines, each contains three numbers x, y and z which means there exists a road between x and y, the distance is zkm (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

分析:在树上选两个点 s,t可以为同一点,使得 w[t] - w[s] - L(s,t)最大。 树形DP,递归。

#include<iostream>#include<stdio.h>#include<algorithm>#include<string.h>#include<vector>const int maxn = 100000;const long long int inf =1e15;typedef long long ll;using namespace std;struct Edge{    int to;    ll w;};int n;ll w[maxn+5],d[maxn+5][2],ans;vector<Edge>g[maxn+5];void dfs(int x,int fa){    int l = g[x].size();    ll Mins = -w[x], Maxt = w[x];    for(int i=0; i<l; i++)    {        Edge e = g[x][i];        int y = e.to;        if(e.to==fa) continue;        dfs(y,x);        Mins = max(Mins,d[y][0]-e.w);        Maxt = max(Maxt,d[y][1]-e.w);    }    ans = max(ans,Maxt+Mins);    d[x][0] = max(-w[x],Mins);    d[x][1] = max(w[x],Maxt);}int main(){    int T,x,y;    ll z;    scanf("%d",&T);    while(T--)    {        scanf("%d",&n);        for(int i=1; i<=n; i++) scanf("%I64d",&w[i]), g[i].clear();        for(int i=1; i<n; i++)        {            scanf("%d %d %I64d",&x,&y,&z);            g[x].push_back((Edge)            {                y,z            }), g[y].push_back((Edge)            {                x,z            });        }        ans = 0, dfs(1,-1);        printf("%I64d\n",ans);    }    return 0;}


原创粉丝点击