链接:
http://acm.hdu.edu.cn/showproblem.php?pid=6201
题目:
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
题意:
给你一棵树,树上有点权,要求选择起点S和终点T,求出 max(T−S−sum) ,sum为S到T的边权。
思路:
源点连所有的树上点,边权为 a[i] ,所有树上点在连接汇点,边权为 −a[i] ,然后在根据树建图,spfa跑个最长路即可。
实现:
#include <bits/stdc++.h>
using namespace std;
const int maxn = int(2e6)+7, INF = 0x3f3f3f3f;
long long head_edge[maxn], cnt_edge, n, t, u, v, tmp, S=0, T, dist[maxn];
bitset<maxn> inque;
struct node{
long long next, to, cost;
}edge[maxn];
void addedge(long long u, long long v, long long cost) {
edge[cnt_edge] = {head_edge[u], v, cost};
head_edge[u] = cnt_edge++;
}
long long SPFA(long long S, long long T) {
inque.reset();
memset(dist, -INF, sizeof(dist));
dist[S] = 0, inque[S] = 1;
queue<int> q;
q.push(S);
while(!q.empty()) {
u = q.front(), q.pop();
inque[u] = 0;
for(long long i=head_edge[u] ; ~i ; i=edge[i].next) {
v = edge[i].to;
if(dist[v] < dist[u] + edge[i].cost) {
dist[v] = dist[u] + edge[i].cost;
if(!inque[v]) {
q.push(v);
inque[v] = 1;
}
}
}
}
return dist[T];
}
void init() {
memset(head_edge, -1, sizeof(head_edge));
cnt_edge = 0;
}
int main() {
scanf("%lld", &t);
while(init(), t--) {
scanf("%lld", &n);
T = n+1;
for(long long i=1 ; i<=n ; i++) {
scanf("%lld", &tmp);
addedge(S, i, -tmp);
addedge(i, T, tmp);
}
for(long long i=1 ; i<n ; i++) {
scanf("%lld%lld%lld", &u, &v, &tmp);
addedge(u, v, -tmp);
addedge(v, u, -tmp);
}
printf("%lld\n",SPFA(S, T));
}
return 0;
}