transaction transaction transaction HDU

来源:互联网 发布:淘宝店铺没有访客流量 编辑:程序博客网 时间:2024/06/05 09:00

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 iitt city. Kelukin will take taxi, whose price is 1yuan per km and this fare cannot be ignored.
There are n−1roads 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 nn (2≤n≤100000) means the number of cities;
second line contains nn numbers, the iithth number means the prices in iithth city; (1≤Price≤10000)
then follows n−1 lines, each contains three numbers x, y and z which means there exists a road between xx and yy, the distance is zzkm (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
这题真的可以,考的是怎么建图,的确现在图论很多题都是这么建图的,我一直忽略这点,一直以为网络才这么考的,自己看问题太容易被限制了,这里虚设了一个源点(0)和一个汇点(n+1),所有的点和0连边,边权威ai,所有点和n+1连边,边权为-ai,其他点与点之间的边权改为-w。

#include<iostream>#include<cstdio>#include<algorithm>#include<cstring>#include<vector>#include<queue>#define N 100005#define mod 530600414using namespace std;int n;vector<int> graph[N];queue<int> que;int dis[N];bool inQ[N];struct node{    int to,w;}edge[400005];int k;void spfa(){    for(int i=0;i<=n+1;i++)        dis[i]=-100000000;    dis[0]=0;    que.push(0);    inQ[0]=true;    while(!que.empty())    {        int u=que.front();        que.pop();        inQ[u]=false;        for(int i=0;i<graph[u].size();i++)        {            int index=graph[u][i];            int v=edge[index].to;            if(dis[v]<dis[u]+edge[index].w)            {                dis[v]=dis[u]+edge[index].w;                if(!inQ[v])                {                    que.push(v);                    inQ[v]=true;                }            }        }    }}void addEdge(int x,int y,int w){    edge[k].to=y;    edge[k].w=w;    graph[x].push_back(k);    k++;}int main(){    int t;    int x,y;    scanf("%d",&t);    int w;    while(t--)    {        scanf("%d",&n);        for(int i=0;i<=n+1;i++)            graph[i].clear();        k=0;        for(int i=1;i<=n;i++)        {            scanf("%d",&w);            addEdge(0,i,w);            addEdge(i,n+1,-w);        }        for(int i=1;i<n;i++)        {            scanf("%d%d%d",&x,&y,&w);            addEdge(x,y,-w);            addEdge(y,x,-w);        }        spfa();        printf("%d\n",dis[n+1]);    }    return 0;}
原创粉丝点击