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 aiai yuanyuan in iitt city. Kelukin will take taxi, whose price is 11yuanyuan per km and this fare cannot be ignored.
There are n−1n−1 roads connecting nn 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 TT (1≤T≤101≤T≤10) , the number of test cases.
For each test case:
first line contains an integer nn (2≤n≤1000002≤n≤100000) means the number of cities;
second line contains nn numbers, the iithth number means the prices in iithth city; (1≤Price≤10000)(1≤Price≤10000)
then follows n−1n−1 lines, each contains three numbers xx, yy and zz which means there exists a road between xx and yy, the distance is zzkmkm (1≤z≤1000)(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 10Sample Output
8题意:
给出N个点的一棵树,已知两点间距离,也知道每个点的点权值,点权值代表在这个点买或者卖物品花费的或者是得到的钱数、
我们现在只能在一个点购买物品,在一个点卖出物品,问最大的利润。
我们建立一个源点,使得源点连入各个点,花费是-val【i】,表示我们想要从这个点作为出发点的花费,然后再建立一个汇点,让各个点连入这个点,花费是val【i】,表示我们想要从这个点作为终点的利润。
AC代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<vector>
#include<stdlib.h>
#include<queue>
#include<set>
#include<iomanip>
#include<math.h>
using namespace std;
typedef long long ll;
typedef double ld;
const ll INF = 1e18;
ll cont,ss,tt;
ll a[150000];
ll head[150000];
ll vis[150000];
ll dist[150000];
struct node
{
ll from,to,next,w;
} e[100005*7];
void add(ll from,ll to,ll w)
{
e[cont].to=to;
e[cont].w=w;
e[cont].next=head[from];
head[from]=cont++;
}
void SPFA()
{
queue<ll>s;
memset(vis,0,sizeof(vis));
for(ll i=0; i<=tt; i++)
dist[i]=-INF;
dist[0]=0;
s.push(0);
while(!s.empty())
{
ll u=s.front();
vis[u]=0;
s.pop();
for(ll i=head[u]; i!=-1; i=e[i].next)
{
ll v=e[i].to;
ll w=e[i].w;
if(dist[v]<dist[u]+w)
{
dist[v]=dist[u]+w;
if(vis[v]==0)
{
vis[v]=1;
s.push(v);
}
}
}
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
cont=0;
memset(head,-1,sizeof(head));
ll n;
scanf("%lld",&n);
for(ll i=1; i<=n; i++)
scanf("%lld",&a[i]);
for(ll i=1; i<=n-1; i++)
{
ll x,y,w;
scanf("%lld%lld%lld",&x,&y,&w);
add(x,y,-w);
add(y,x,-w);
}
ss=0,tt=n+1;
for(ll i=1; i<=n; i++)
add(ss,i,-a[i]);
for(ll i=1; i<=n; i++)
add(i,tt,a[i]);
SPFA();
printf("%lld\n",dist[tt]);
}
return 0;
}