您的位置:首页 > 其它

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

2017-09-10 18:14 453 查看


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 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

思路:以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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐