Description
One cow from each of N farms (1 ≤ N ≤ 1000) conveniently numbered 1..N is going to attend the big cow party to be held at farm #X (1 ≤ X ≤ N). A total of M (1 ≤ M ≤ 100,000) unidirectional (one-way roads connects pairs of farms; road i requires Ti (1 ≤ Ti ≤ 100) units of time to traverse.
Each cow must walk to the party and, when the party is over, return to her farm. Each cow is lazy and thus picks an optimal route with the shortest time. A cow's return route might be different from her original route to the party since roads are one-way.
Of all the cows, what is the longest amount of time a cow must spend walking to the party and back?
Input
Lines 2.. M+1: Line i+1 describes road i with three space-separated integers: Ai, Bi, and Ti. The described road runs from farm Ai to farm Bi, requiring Ti time units to traverse.
Output
Sample Input
4 8 2 1 2 4 1 3 2 1 4 7 2 1 1 2 3 5 3 1 2 3 4 4 4 2 3
Sample Output
10
Hint
题意:每一个点到点x 和返回的原点的最短路径,求出其中最大值。注意输入为有向边。
思路:一开始使用floyd 算法超时了,改换成dijkstra算法,求出确定点的最短路径。
CODE:
#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
const int inf = 0xffffff;
const int MAX = 1005;
int n, m, x;
struct edge {int to, cost;} ;
typedef pair<int, int> P;
vector<edge> g[MAX];
int d[MAX], ans[MAX];
void dijkstra(int s)
{
priority_queue<P, vector<P>, greater<P> > que;
fill(d, d + n + 1, inf);
d[s] = 0;
que.push(P(0, s));
while(!que.empty()) {
P p = que.top(); que.pop();
int v = p.second;
if(d[v] < p.first) continue;
for(int i = 0; i < g[v].size(); ++i) {
edge e = g[v][i];
if(d[e.to] > d[v] + e.cost) {
d[e.to] = d[v] + e.cost;
que.push(P(d[e.to], e.to));
}
}
}
}
int main()
{
//freopen("in", "r", stdin);
while(~scanf("%d %d %d", &n, &m, &x)) {
for(int i = 0; i < m; ++i) {
int a, b, t;
edge w;
scanf("%d %d %d", &a, &b, &t);
w.to = b; w.cost = t;
g[a].push_back(w);
}
dijkstra(x);
for(int i = 1; i <= n; ++i) {
ans[i] = d[i];
}
for(int i = 1; i <= n; ++i) {
dijkstra(i);
ans[i] += d[x];
}
sort(ans, ans + n + 1);
printf("%d\n", ans[n]);
}
return 0;
}