transaction transaction transaction
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 132768/132768 K (Java/Others)
Total Submission(s): 349 Accepted Submission(s): 165
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
Source
2017 ACM/ICPC Asia Regional Shenyang Online
题意: n个城市,每个城市有自己的书价,你在任意一个城市购买一本书,在任意一个城市出售,问你能赚的钱,城市之间的路有花费。
题解:建一个源点到每个城市,花费为城市书价,建一个汇点链接每个城市,花费为-城市书价,城市之间建无向边,跑一边最短路取反即可(建相反边的原因是避免负权环的存在)
代码:
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<vector>
#include<queue>
#include<set>
#include<algorithm>
#include<map>
#include<math.h>
using namespace std;
typedef long long int ll;
typedef pair<int,int>pa;
const int N=1e6+100;
const int mod=1e9+7;
const ll INF=1e18;
int read()
{
int x=0;
char ch = getchar();
while('0'>ch||ch>'9')ch=getchar();
while('0'<=ch&&ch<='9')
{
x=(x<<3)+(x<<1)+ch-'0';
ch=getchar();
}
return x;
}
/***********************************************************/
struct node
{
int to,next,w;
}edge[N<<2];
int cnt;
int t,n,x,y,z;
int head[N<<2];
int vis[N];
int dis[N];
void add(int f,int to,int w)
{
edge[cnt].to=to;
edge[cnt].w=w;
edge[cnt].next=head[f];
head[f]=cnt++;
}
int main()
{
scanf("%d",&t);
while(t--)
{
cnt=0;
memset(head,-1,sizeof(head));
memset(vis,0,sizeof(vis));
memset(dis,0x3f,sizeof(dis));
scanf("%d",&n);
int ss=n+1;
int tt=ss+1;
for(int i=1;i<=n;i++)
{
scanf("%d",&x);
add(ss,i,x);
add(i,tt,-x);
}
for(int i=1;i<n;i++)
{
scanf("%d%d%d",&x,&y,&z);
add(x,y,z);
add(y,x,z);
}
queue<int>q;
q.push(ss);
vis[ss]=1;
dis[ss]=0;
while(!q.empty())
{
int u=q.front();
q.pop();
vis[u]=0;
for(int i=head[u];i!=-1;i=edge[i].next)
{
int v=edge[i].to;
int w=edge[i].w;
if(dis[u]+w<dis[v])
{
dis[v]=dis[u]+w;
if(!vis[v])
{
vis[v]=1;
q.push(v);
}
}
}
}
printf("%d\n",-dis[tt]);
}
}