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 Titime 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 +反向图
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <iostream>
using namespace std;
#define INF 0x7F800000
int mtx[1005][1005];
int mtx1[1005][1005];
int be[1005];
int vis[1005];
int dist[1005];
int ans1[1005];
int ans2[1005];
int main()
{
int t,n,i,p,j,k,m,kk,x,pp,begin,end,kkpp,w,s,ans;
while( scanf("%d%d%d",&n,&m,&x)!=EOF)
{
memset(mtx,0,sizeof(mtx));
memset(vis,0,sizeof(vis));
memset(dist,0,sizeof(dist));
int minway;
for (p=1;p<=m;p++)
{
scanf("%d%d",&pp,&kk);
scanf("%d",&kkpp);
if ( mtx[kk][pp]==0)
{
mtx[kk][pp]=kkpp;
}
if (kkpp<mtx[kk][pp] && mtx[kk][pp]!=0)
{
mtx[kk][pp]=kkpp;
}
}
begin=x;
vis[begin]=1;
for (j=1;j<=n;j++) //创建第一组dist
{
if ( (mtx[begin][j])!=0 || (begin==j) )
dist[j]=mtx[begin][j];
else
dist[j]=INF;
}
for (k=1;k<=n;k++) //不断更新dist
{
minway=INF;
int minpoint;
for (j=1;j<=n;j++) //不断更新dist
{
if ( vis[j]==0 && dist[j]<minway ) //找到最小加权边与点
{
minway=dist[j];
minpoint=j;
}
}
if(minway == INF) break; //HEHE
vis[minpoint]=1;
for (j=1;j<=n;j++) //不断更新dist
{
if (mtx[minpoint][j]+minway<dist[j]&&vis[j]!=1&&mtx[minpoint][j]!=0)
dist[j]=mtx[minpoint][j]+minway;
}
}
for (i=1;i<=n;i++)
{
ans1[i]=dist[i];
} //来表
for (p=1;p<=n;p++) //构建反向表
{
for (i=1;i<=n;i++)
{
mtx1[i][p]=mtx[p][i];
}
}
memset(vis,0,sizeof(vis)); //初始化
memset(dist,0,sizeof(dist)); //初始化
begin=x;
vis[begin]=1;
for (j=1;j<=n;j++) //创建第一组dist
{
if ( (mtx1[begin][j])!=0 || (begin==j) )
dist[j]=mtx1[begin][j];
else
dist[j]=INF;
}
for (k=1;k<=n;k++) //不断更新dist
{
minway=INF;
int minpoint;
for (j=1;j<=n;j++) //不断更新dist
{
if ( vis[j]==0 && dist[j]<minway ) //找到最小加权边与点
{
minway=dist[j];
minpoint=j;
}
}
if(minway == INF) break; //HEHE
vis[minpoint]=1;
for (j=1;j<=n;j++) //不断更新dist
{
if (mtx1[minpoint][j]+minway<dist[j]&&vis[j]!=1&&mtx1[minpoint][j]!=0)
dist[j]=mtx1[minpoint][j]+minway;
}
}
for (p=1;p<=n;p++) //去表
{
ans2[p]=dist[p];
}
int tmp=0;
for (p=1;p<=n;p++) //总表
{
if (ans2[p]+ans1[p]>tmp )
tmp=ans2[p]+ans1[p];
}
printf("%d\n",tmp);
}
return 0;
}