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; roadi requiresTi (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?
InputLines 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.
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
10
本题类似于 次小生成树----hpu王小二,都是同样的程序跑了两次,异曲同工吧;
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#define INF 0x3f3f3f3f
using namespace std;
int graph[1010][1010],lowcost[1010],low[1010],mst[1010];
int x,n,m;
void dij(int v)//dijkstra模板;
{
int i,j,min,minid;
memset(mst,0,sizeof(mst));
mst[v]=1;
for(i=1;i<=n;i++)
lowcost[i]=graph[v][i];
for(i=2;i<=n;i++)
{
min=INF;
for(j=1;j<=n;j++)
{
if(!mst[j] && lowcost[j]<min)
{
min=lowcost[j];
minid=j;
}
}
mst[minid]=1;
for(j=1;j<=n;j++)
{
if(!mst[j] && lowcost[j]>graph[minid][j]+lowcost[minid])
lowcost[j]=graph[minid][j]+lowcost[minid];
}
}
}
int main()
{
int i,j,time,wa;
while(scanf("%d %d %d",&n,&m,&x)!=EOF)
{
memset(graph,INF,sizeof(graph));
while(m--)
{
scanf("%d %d %d",&i,&j,&time);
if(time<graph[i][j])
graph[i][j]=time;//单向路径;
}
dij(x);//计算牛回去的最短时间;
for(i=1;i<=n;i++)//执行完dij,lowcost[i]代表以x为起点,i为终点的最短路径;
low[i]=lowcost[i];
for(i=1;i<=n;i++)
{
for(j=i+1;j<=n;j++)//j不能从1开始,否则反转两次,相当于没变化;
{
wa=graph[j][i];
graph[j][i]=graph[i][j];
graph[i][j]=wa;
}
}
dij(x);
int maxn=0,ans;
for(i=1;i<=n;i++)
{
if(i!=x)//此条件不可少;
ans=low[i]+lowcost[i];//来回时间相加;
maxn=max(maxn,ans);
}
printf("%d\n",maxn);
}
return 0;
}
bellman-ford,思路一样,只是换种方式,和dijkstra 时间差不多;
#include<stdio.h>
#include<string.h>
#define INF 0x3f3f3f3f
int mst[300000],mst1[300000];
int n,m,x;
struct node
{
int a;
int b;
int c;
}s[300000];
void bellman_ford(int v)
{
memset(mst,INF,sizeof(mst));
mst[v]=0;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
if(mst[s[j].a]>s[j].c+mst[s[j].b])//单向路径;
mst[s[j].a]=s[j].c+mst[s[j].b];
}
}
}
int main()
{
int a,b,c,wa;
while(scanf("%d %d %d",&n,&m,&x)!=EOF)
{
for(int i=1;i<=m;i++)
scanf("%d %d %d",&s[i].a,&s[i].b,&s[i].c);
bellman_ford(x);
for(int i=1;i<=n;i++)//去的最短路径;
mst1[i]=mst[i];
for(int i=1;i<=m;i++)//置换一下;
{
wa=s[i].a;
s[i].a=s[i].b;
s[i].b=wa;
}
bellman_ford(x);//计算回来的最短路径;
int ans,maxn=0;
for(int i=1;i<=n;i++)
{
if(i!=x)
ans=mst[i]+mst1[i];
if(ans>maxn) maxn=ans;
}
printf("%d\n",maxn);
}
return 0;
}