2017 ACM/ICPC Asia Regional Shenyang Online:transaction transaction transaction

来源:互联网 发布:关于初中语文的软件 编辑:程序博客网 时间:2024/06/08 03:04

transaction transaction transaction

                                                               Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 132768/132768 K (Java/Others)
                                                                                          Total Submission(s): 29    Accepted Submission(s): 13


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

思路:以1节点为根,dfs其子节点,用dmax[k]表示以k节点为根的子树中所能卖的最大价格,dmin[k]表示买书花费的最少价格,ans=max(dmax[k]-dmin[k])。边的花费加到dmax和dmin里面就行。

#include<bits/stdc++.h>using namespace std;const int MAX=5e6+10;struct Edge{int to,next,w;}ed[MAX];int head[MAX],tot,ans,v[MAX];int dmax[MAX],dmin[MAX],a[MAX];void add(int x,int y,int z){ed[tot].to = y;ed[tot].next = head[x];ed[tot].w=z;head[x]=tot++;}void dfs(int k){    v[k]=1;    dmax[k]=a[k];    dmin[k]=a[k];    for(int i=head[k];i!=-1;i=ed[i].next)    {        int nex=ed[i].to;        if(v[nex])continue;        dfs(nex);        dmax[k]=max(dmax[k],dmax[nex]-ed[i].w);        dmin[k]=min(dmin[k],dmin[nex]+ed[i].w);        ans=max(ans,dmax[k]-dmin[k]);    }    ans=max(ans,dmax[k]-dmin[k]);}int main(){    int T,n;cin>>T;    while(T--)    {        memset(head,-1,sizeof head);        memset(v,0,sizeof v);        tot=0;        ans=-1e9-7;        scanf("%d",&n);        for(int i=1;i<=n;i++)scanf("%d",&a[i]);        for(int i=1;i<n;i++)        {            int x,y,z;            scanf("%d%d%d",&x,&y,&z);            add(x,y,z);            add(y,x,z);        }        dfs(1);        printf("%d\n",ans);    }    return 0;}



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