POJ3268 Silver Cow Party —— 最短路
题目链接:http://poj.org/problem?id=3268
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 24527 | Accepted: 11164 |
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
Source
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 #include <vector> 6 #include <cmath> 7 #include <queue> 8 #include <stack> 9 #include <map> 10 #include <string> 11 #include <set> 12 #define rep(i,a,n) for(int (i) = a; (i)<=(n); (i)++) 13 #define ms(a,b) memset((a),(b),sizeof((a))) 14 using namespace std; 15 typedef long long LL; 16 const double EPS = 1e-8; 17 const int INF = 2e9; 18 const LL LNF = 9e18; 19 const int MOD = 1e9+7; 20 const int MAXN = 1e3+10; 21 22 int n, m, X; 23 int g[MAXN][MAXN]; 24 25 int dis1[MAXN], dis2[MAXN]; 26 bool vis[MAXN]; 27 void dijkstra(int st, int dis[]) 28 { 29 memset(vis, 0, sizeof(vis)); 30 for(int i = 1; i<=n; i++) 31 dis[i] = (i==st?0:INF); 32 33 for(int i = 1; i<=n; i++) 34 { 35 int k, minn = INF; 36 for(int j = 1; j<=n; j++) 37 if(!vis[j] && dis[j]<minn) 38 minn = dis[k=j]; 39 40 vis[k] = 1; 41 for(int j = 1; j<=n; j++) 42 if(!vis[j] && g[k][j]!=INF) 43 dis[j] = min(dis[j], dis[k]+g[k][j]); 44 } 45 } 46 47 int main() 48 { 49 while(scanf("%d%d%d", &n, &m, &X)!=EOF) 50 { 51 for(int i = 1; i<=n; i++) 52 for(int j = 1; j<=n; j++) 53 g[i][j] = INF; 54 for(int i = 1; i<=m; i++) 55 { 56 int u, v, w; 57 scanf("%d%d%d", &u, &v, &w); 58 g[u][v] = w; 59 } 60 dijkstra(X, dis1); //第一次跑最短路,计算X到各点的最短距离 61 62 for(int i = 1; i<=n; i++) //将边取反 63 for(int j = i+1; j<=n; j++) 64 swap(g[i][j], g[j][i]); 65 dijkstra(X, dis2); //第二次跑最短路,计算X到各点的距离,但因为边取反了,所以实际上是各点到X的最短距离。 66 67 int ans = 0; 68 for(int i = 1; i<=n; i++) //取两段距离之和的最大值 69 ans = max(ans, dis1[i]+dis2[i]); 70 printf("%d\n", ans); 71 } 72 }