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
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只来自N个牛场的牛(标号1~N)去位于标记为x的农场参加派对,问你去和返回的最小花费,图是有向图。
思路
因为要求牛去派对和从派对回到起点的最小花费,所以需要两次dij,返回可以将邻接矩阵倒置,跑一遍dij即为返回时的最短路。
如果有对dij及dij各种优化不熟悉的可以参考:Dij及各种优化
代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int maxn=1005;
const int maxe=100000+5;
const int INF=0x3f3f3f3f;
struct proc
{
int v,w;
int next;
int op;
proc():op(0) {}
};
struct pri_queue
{
int v,dis;
pri_queue(int a,int b):v(a),dis(b) {}
friend bool operator < (const pri_queue &n1,const pri_queue &n2)
{
return n1.dis>n2.dis;
}
};
int head[maxn],vis[maxn],cnt,fdis[maxn],dis[maxn],n,m,x;
proc edge[2*maxe];
void addEdge(int u,int v,int w)//建立邻接表
{
edge[cnt].v=v;
edge[cnt].w=w;
edge[cnt].op=0;
edge[cnt].next=head[u];
head[u]=cnt++;
edge[cnt].v=u;
edge[cnt].w=w;
edge[cnt].op=1;
edge[cnt].next=head[v];
head[v]=cnt++;
}
int queue_dij(int s,int z)
{
memset(vis,0,sizeof(vis));
for(int i=0;i<=n;i++)
{
dis[i]=INF;
}
priority_queue<pri_queue> q;
dis[s]=0;
pri_queue pre(s,0);
q.push(pre);
while(!q.empty())
{
pre=q.top();
q.pop();
vis[pre.v]=1;
for(int i=head[pre.v];i!=-1;i=edge[i].next)
{
if(z==0)
{
if(edge[i].op) continue;
}
else if(z==1)
{
if(!edge[i].op) continue;
}
if(!vis[edge[i].v]&&dis[pre.v]+edge[i].w<dis[edge[i].v])
{
dis[edge[i].v]=dis[pre.v]+edge[i].w;
pri_queue tmp(edge[i].v,dis[edge[i].v]);
q.push(tmp);
}
}
}
//寻找最大的一个花费
int maxx=0;
if(!z)
{
for(int i=1;i<=n;i++)
{
fdis[i]=dis[i];
}
}
else
{
for(int i=1;i<=n;i++)
{
if(fdis[i]+dis[i]>maxx)
maxx=fdis[i]+dis[i];
}
}
return maxx;
}
int main()
{
while(~scanf("%d %d %d",&n,&m,&x))
{
cnt=0;
for(int i=0;i<=n;i++)
{
head[i]=-1;
}
int s,e,val;
for(int i=0;i<m;i++)
{
scanf("%d %d %d",&s,&e,&val);
addEdge(s,e,val);
}
queue_dij(x,0);
int ans=queue_dij(x,1);
printf("%d\n",ans);
}
return 0;
}