当前位置: 代码迷 >> 综合 >> POJ 3268 Silver Cow Party(最短路径之迪杰斯特拉算法)
  详细解决方案

POJ 3268 Silver Cow Party(最短路径之迪杰斯特拉算法)

热度:39   发布时间:2023-11-17 14:30:25.0

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:  NM, 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
Hint
Cow 4 proceeds directly to the party (3 units) and returns via farms 1 and 3 (7 units), for a total of 10 time units.

题解:

只要正着求一遍最短路数组倒置再求一遍最短路,求出相加之和最大的那个就好了

代码:

#include<algorithm>
#include<iostream>
#include<cstring>
#include<stdio.h>
#include<math.h>
#include<string>
#include<stdio.h>
#include<queue>
#include<stack>
#include<map>
#include<deque>
#define M (t[k].l+t[k].r)/2
#define lson k*2
#define rson k*2+1
using namespace std;
const int INF=100861111;
int p[1005][1005];//存图
int dis1[1005];//存第一次最短路结果
int dis2[1005];//第二次最短路结果
int vis[1005];//遍历数组
int main()
{int i,j,k,n,m,test,x,a,b,c,time=0,key,minn;scanf("%d%d%d",&n,&m,&x);for(i=1;i<=n;i++){dis1[i]=INF;dis2[i]=INF;vis[i]=0;for(j=1;j<=n;j++)p[i][j]=INF;}for(i=0;i<m;i++){scanf("%d%d%d",&a,&b,&c);p[a][b]=c;}dis1[x]=0;key=x;for(i=1;i<=n;i++)//正向最短路{minn=INF;for(j=1;j<=n;j++){if(!vis[j]&&dis1[j]<minn){minn=dis1[j];key=j;}}vis[key]=1;for(j=1;j<=n;j++){if(minn+p[key][j]<dis1[j])dis1[j]=minn+p[key][j];}}for(i=1;i<=n;i++){vis[i]=0;}dis2[x]=0;key=x;for(i=1;i<=n;i++){minn=INF;for(j=1;j<=n;j++){if(!vis[j]&&dis2[j]<minn){minn=dis2[j];key=j;}}vis[key]=1;for(j=1;j<=n;j++){if(minn+p[j][key]<dis2[j])//反过来求一遍dis2[j]=minn+p[j][key];}}minn=0;for(i=1;i<=n;i++)//取相加最大{if(minn<dis1[i]+dis2[i])minn=dis1[i]+dis2[i];}printf("%d\n",minn);return 0;
}