DIJ-Silver Cow Party POJ - 3268
题目:
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: N, M, 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.
题意:
输入奶牛数量N,农场数量M,party位置X。
接着输入M行各农场之间起点、终点、所需要花费的时间。
问,所有奶牛到农场X开party,所需花费最短时间的最大值(最少需要花费多少时间,使得所有奶牛到农场X,再从农场X回家)
思路:
与一般问题略有区别的地方是回家,只需要在调用dij函数时将起点和终点对换,再调用一次dij,然后记录每头牛所需花费的最短时间,不断更新最终得到最短时间的最大值。
代码:
#include <iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
#define inf 0x3f3f3f3f
#define P pair<int,int>
using namespace std;
const int maxn=1e3+5;
const int maxm=1e5+5;
int N,M,X,k=0,s,e,ans=-inf;
int head[maxn],d[maxn];
bool vis[maxn];struct node
{int v,next,w;
}a[maxm];void add(int u,int v,int w)
{a[++k].next=head[u];a[k].v=v;a[k].w=w;head[u]=k;
}void dij()
{memset(d,inf,sizeof(d));memset(vis,false,sizeof(vis));d[s]=0;priority_queue<P,vector<P>,greater<P> >q;q.push(make_pair(0,s));while(q.size()){int u=q.top().second;q.pop();if(vis[u]) continue;vis[u]=true;for(int i=head[u];i;i=a[i].next){int v=a[i].v,w=a[i].w;if(d[v]>d[u]+w)d[v]=d[u]+w,q.push(make_pair(d[v],v));}}
}
int main()
{cin>>N>>M>>X;for(int i=0;i<M;i++){int u,v,w;scanf("%d%d%d",&u,&v,&w);add(u,v,w);}for(int i=1;i<=N;i++){if(i==X) continue;int tmp=0;s=i,e=X;dij();tmp+=d[e];s=X,e=i;dij();tmp+=d[e];if(ans<tmp) ans=tmp;}cout<<ans<<endl;return 0;
}