当前位置: 代码迷 >> 综合 >> POJ-3268-Disease Management-(最短路径spfa)
  详细解决方案

POJ-3268-Disease Management-(最短路径spfa)

热度:71   发布时间:2024-01-12 15:50:41.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.


是很典型的最短路径问题,只不过这里是来回的,路径的单向的,为了不超时用了效率较高的SPFA,先求x点到每点的最短路径(以x点为起点SPFA一次),然后求每个点到x点的最短路径(以每个点为起点SPFA一次),然后相加找最大

代码:

#include<iostream>
#include<string>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<queue>
#include<cstring>
#include<map>
#include<vector>
using namespace std;
typedef long long ll;
#define M 102
int n,m,x;
int ans[1005],dis[1005],team[2050],num[1005],a[1005][1005],w[1005][1005];
bool vis[1005];
int main()
{int i,j,k,u,s,e,t;scanf("%d%d%d",&n,&m,&x);memset(w,0x7f,sizeof(w));for(i=1;i<=m;i++){scanf("%d%d%d",&s,&e,&t);a[s][num[s]++]=e;w[s][e]=t;}memset(dis,0x7f,sizeof(dis));dis[x]=0;memset(vis,false,sizeof(vis));team[1]=x; vis[x]=true;int head=0,tail=1;do{head++;head=((head-1)%2050)+1;u=team[head];vis[u]=false;for(j=0;j<num[u];j++)if(dis[a[u][j]]>dis[u]+w[u][a[u][j]]){dis[a[u][j]]=dis[u]+w[u][a[u][j]];if(!vis[a[u][j]]){tail++;head=((head-1)%2050)+1;team[tail]=a[u][j];vis[a[u][j]]=true;}}}while(head!=tail);for(i=1;i<=n;i++)ans[i]=dis[i];for(i=1;i<=n;i++){if(i==x) continue;memset(team,0,sizeof(team));memset(dis,0x7f,sizeof(dis));dis[i]=0;memset(vis,false,sizeof(vis));team[1]=i; vis[i]=true;int head=0,tail=1;do{head++;head=((head-1)%2050)+1;u=team[head];vis[u]=false;for(j=0;j<num[u];j++)if(dis[a[u][j]]>dis[u]+w[u][a[u][j]]){dis[a[u][j]]=dis[u]+w[u][a[u][j]];if(!vis[a[u][j]]){tail++;head=((head-1)%2050)+1;team[tail]=a[u][j];vis[a[u][j]]=true;}}}while(head!=tail);ans[i]+=dis[x];}int maxn=0;for(i=1;i<=n;i++)if(ans[i]>maxn) maxn=ans[i];printf("%d\n",maxn);return 0;
}


  相关解决方案