【2017沈阳网络赛】1008 hdu6201 transaction transaction transaction 树形dp

来源:互联网 发布:wpf数据绑定详解 编辑:程序博客网 时间:2024/05/22 05:12

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 n1 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 (1T10) , the number of test cases.  
For each test case:
first line contains an integer n (2n100000) means the number of cities;
second line contains n numbers, the ith number means the prices in ith city; (1Price10000) 
then follows n1 lines, each contains three numbers xy and z which means there exists a road between x and y, the distance is zkm (1z1000)
 

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 301 3 23 4 10
 

Sample Output
8
 

题意:

给出一棵树,每个点都有点权,问取两个点,使得T-S-sumw为最大(T为终点的点权,S为起点的点权,sumw为S到T的路径长度),可取相同的点。


思路:

树形dp,设d[t][0]为节点t的最大值,d[t][1]为最小值。


////  main.cpp//  1008////  Created by zc on 2017/9/10.//  Copyright © 2017年 zc. All rights reserved.//#include <iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<cmath>#include<vector>#define ll long longusing namespace std;const int N=110000;int n,a[N],d[N][2],ans;vector<pair<int,int> >r[N];void dfs(int t,int fa){    int mmax=a[t],mmin=a[t];    for(int i=0;i<r[t].size();i++)    {        int j=r[t][i].first;        if(j==fa)   continue;        dfs(j,t);        if(mmax<d[j][0]-r[t][i].second) mmax=d[j][0]-r[t][i].second;        if(mmin>d[j][1]+r[t][i].second) mmin=d[j][1]+r[t][i].second;    }    ans=max(ans,mmax-mmin);    d[t][0]=mmax;    d[t][1]=mmin;}int main(int argc, const char * argv[]) {    int T;    scanf("%d",&T);    while(T--)    {        scanf("%d",&n);        for(int i=1;i<=n;i++)   scanf("%d",&a[i]);        for(int i=1;i<=n;i++)   r[i].clear();        for(int i=0;i<n-1;i++)        {            int x,y,z;            scanf("%d%d%d",&x,&y,&z);            r[x].push_back(make_pair(y,z));            r[y].push_back(make_pair(x,z));        }        ans=0;        memset(d,0,sizeof(d));        dfs(1,-1);        printf("%d\n",ans);    }}

阅读全文
0 0
原创粉丝点击