Silver Cow Party
Time Limit: 2000MS Memory Limit: 65536
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
Line 1: Three space-separated integers, respectively: N, M, and X
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
Line 1: One integer: the maximum of time any one cow must walk.
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
这题要求一个所有点到x点,再回到各自出发的点。输出路程最远的往返路途。
由于有向图,dijkstra求x点返回时的点好办,但是怎么求其他点来x的时候的最短路途呢?现有算法全都是求一个点到其他所有点的最短路,要求其他点到一个点的算法,比如flody算法O(n^3)妥妥超时。其实解决办法很简单。
只要将所有的边反转,然后直接求一个x点到其他点的最短距离就是其他点到x点的最短距离了,其实就是将有向图看成无向图。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#define inf 0x3f3f3f3f
using namespace std;
int map[1005][1005];
struct cmp
{
bool operator()(int a,int b)const{
return a>b;
}
};
void init (int map[][1005])
{
for (int i = 0;i < 1005; i++){
for (int j = 0; j< 1005; j++){
if (i == j){
map[i][j] = 0;
}
else{
map[i][j] = inf;
}
}
}
}
int dijkstra (int m,int w)
{
int dis[1005],dis_back[1005];
bool vis[1005] = {false};
int ans = 0;
memset(vis,false,sizeof vis);
for (int i = 1;i <= m; i++){
dis_back[i] = map[w][i];
}
vis[w] = true;
for (int i = 1; i < m; i++){
int total,cut = inf;
for (int i = 1; i <= m; i++){
if (!vis[i] && cut > dis_back[i]){
cut = dis_back[i];
total = i;
}
}
//cout << total << endl;
vis[total] = true;
for (int j = 1; j <= m; j++){
if (!vis[j] && dis_back[j] > dis_back[total] + map[total][j]){
dis_back[j] = dis_back[total] + map[total][j];
}
}
}
memset(vis,false,sizeof vis);
for (int i = 1;i <= m; i++){
dis[i] = map[i][w];
}
vis[w] = true;
for (int i = 1;i < m; i++){
int cut = inf,total;
for (int j = 1;j <= m; j++){
if (!vis[j] && cut > dis[j]){
cut = dis[j];
total = j;
}
}
//cout << total << endl;
vis[total] = true;
for (int j = 1; j <= m; j++){
if (!vis[j] && dis[j] > dis[total] + map[j][total]){
dis[j] = dis[total] + map[j][total];
}
}
}
for (int i = 1; i <= m; i++){
if (dis[i]+dis_back[i] > ans){
ans = dis[i]+dis_back[i];
}
}
return ans;
}
int main ()
{
int m,n,total;
scanf ("%d%d%d",&m,&n,&total);
init(map);
for (int i = 0;i < n; i++){
int a,b,c;
scanf ("%d%d%d",&a,&b,&c);
if (map[a][b] > c){
map[a][b] = c;
}
}
cout << dijkstra(m,total) << endl;
return 0;
}