Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 33100 | Accepted: 14813 |
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
题意:
n个人分别住在1~n个点,他们要去某个点聚会并且结束后返回家中.
求每个人的最短路程. (往返路径可以不一样).输出最长的那一个.
思路:
先用dijkstra求出终点到所有点的最短路径(返程).
再沿着反向路径跑一次dijkstra,求出所有点到终点的最短路径.
AC代码:
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <cmath>
#include <cstdio>
#define mem(a, b) memset(a, b, sizeof(a))
#define PI 3.1415926535
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const long long LLINF = 0x3f3f3f3f3f3f3f3f;
const int MAXn = 1005;
const int mod = 1;
int n, m, k;
int w[MAXn][MAXn]; //a->b的距离
bool v[MAXn]; //标记
int d[MAXn]; //终点到所有点的最小距离
int dd[MAXn]; //到终点的最小距离
void Dijkstra(int s,int *d)
{
int i, j;
for (i = 1; i <= n; i++)
d[i] = w[s][i];
mem(v, 0);
v[s] = true;
for (i = 1; i < n; i++)
{
int m = -1, Min = INF;
for (j = 1; j <= n; j++)
{
if (!v[j] && d[j] < Min)
Min = d[m = j];
}
v[m] = true;
for (j = 1; j <= n; j++)
{
d[j] = min(d[j], d[m] + w[m][j]);
}
}
}
int main()
{
scanf("%d%d%d", &n, &m, &k);
int i, a, b, c,j;
mem(w, INF);
for (i = 0; i < MAXn; i++)
w[i][i] = 0;//初始化
for (i = 0; i < m; i++)
{ //输入
scanf("%d%d%d", &a, &b, &c);
if (c < w[a][b])
w[a][b] = c;
}
Dijkstra(k,d); //求终点到所有点的最小距离
for (i = 1; i <= n; i++)
for (j = 1; j < i; j++) //置换矩阵(倒过来)
swap(w[i][j], w[j][i]);
Dijkstra(k,dd);//求所有点到终点的最小距离
int Max = -1;
for (i = 1; i <= n; i++)
{ //求最大值
Max = max(Max, d[i]+dd[i]);
}
printf("%d\n", Max);
return 0;
}