Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 23064 | Accepted: 10550 |
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
三种最短路算法复杂度一比较就知道应该选用dijkstra算法,而由于边是单向的,所以返回路径要单独算,再算一次dijkstra,这是这次把边的起点终点换一下,解决。
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
#define INF 1e9+1
#define MAX_E 100005
#define MAX_V 1005
int cost[MAX_V][MAX_V];
int d[MAX_V];
int d2[MAX_V];
bool used[MAX_V];
int V,M,X;
void init()
{
for(int i=0;i<MAX_V;i++)
{
for(int j=0;j<MAX_V;j++)
{
cost[i][j]=INF;
}
cost[i][i]=0;
}
}
void dijkstra(int s)
{
fill(d,d+V,INF);
fill(used,used+V,false);
d[s]=0;
while(1)
{
int v=-1;
for(int u=0;u<V;u++)
{
if(!used[u]&&(v==-1||d[u]<d[v]))v=u;
}
if(v==-1)break;
used[v]=true;
for(int u=0;u<V;u++)
{
d[u]=min(d[u],d[v]+cost[v][u]);
}
}
}
void Fake_dijkstra(int s)
{
fill(d2,d2+V,INF);
fill(used,used+V,false);
d2[s]=0;
while(1)
{
int v=-1;
for(int u=0;u<V;u++)
{
if(!used[u]&&(v==-1||d2[u]<d2[v]))v=u;
}
if(v==-1)break;
used[v]=true;
for(int u=0;u<V;u++)
{
d2[u]=min(d2[u],d2[v]+cost[u][v]); //将边的起点与终点交换
}
}
}
int main()
{
init();
cin>>V>>M>>X;
int a,b,t;
for(int i=0;i<M;i++)
{
cin>>a>>b>>t;
cost[a-1][b-1]=t;
}
dijkstra(X-1);
Fake_dijkstra(X-1);
int maxt=0;
for(int i=0;i<V;i++)
if(d[i]+d2[i]>maxt)maxt=d[i]+d2[i];
cout<<maxt<<endl;
}