题目里面的路径是单向的,并且是多源到单源,再由单源到多源,这时就可以把转换为两个单源到多源的最短路径的题目,那个多源到单源其实就是单源到多源的逆过程,只需要在记录边的过程中再用另外的容器记录相反方向的边
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?
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.
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
#include<stdio.h>
#include<string.h>
#include<queue>
#define maxr 100005
#define maxf 1005
#define inf 0x3f3f3f3f
using namespace std;
int head[maxf],rehead[maxf];
int n,m,x,dis[maxf],redis[maxf],cnt,recnt;
bool vis[maxf];
struct Edge
{
int v;
int w;
int next;
}edge[maxr],reedge[maxr];
struct list
{
int des;
int weight;
list() { }
list(int a,int b)
{
des=a;
weight=b;
}
friend bool operator <(struct list c,struct list d)
{
return c.weight>d.weight;
}
};
void add_edge(int u,int v,int w)
{
edge[cnt].v=v;
edge[cnt].w=w;
edge[cnt].next=head[u];
head[u]=cnt++;
}
void add_reedge(int u,int v,int w)
{
reedge[recnt].v=v;
reedge[recnt].w=w;
reedge[recnt].next=rehead[u];
rehead[u]=recnt++;
}
void dijkstra(int s)
{
memset(dis,inf,sizeof(dis));
memset(vis,false,sizeof(vis));
priority_queue<struct list> q;
dis[s]=0;
q.push(list(s,dis[s]));
while(!q.empty())
{
struct list Q=q.top();
q.pop();
if(vis[Q.des])
continue;
vis[Q.des]=true;
for(int i=head[Q.des];i!=-1;i=edge[i].next)
{
int to=edge[i].v;
if(dis[to]>dis[Q.des]+edge[i].w)
{
dis[to]=dis[Q.des]+edge[i].w;
q.push(list(to,dis[to]));
}
}
}
}
void redijkstra(int s)
{
memset(redis,inf,sizeof(redis));
memset(vis,false,sizeof(vis));
priority_queue<struct list> q;
redis[s]=0;
q.push(list(s,redis[s]));
while(!q.empty())
{
struct list Q=q.top();
q.pop();
if(vis[Q.des])
continue;
vis[Q.des]=true;
for(int i=rehead[Q.des];i!=-1;i=reedge[i].next)
{
int to=reedge[i].v;
if(redis[to]>redis[Q.des]+reedge[i].w)
{
redis[to]=redis[Q.des]+reedge[i].w;
q.push(list(to,redis[to]));
}
}
}
}
int main()
{
cnt=0;recnt=0;
scanf("%d%d%d",&n,&m,&x);
memset(head,-1,sizeof(head));
memset(rehead,-1,sizeof(rehead));
while(m--)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
add_edge(a,b,c);
add_reedge(b,a,c);
}
dijkstra(x);
redijkstra(x);
int _max=-1;
for(int i=1;i<=n;i++)
{
if(_max<dis[i]+redis[i])
_max=dis[i]+redis[i];
}
printf("%d",_max);
return 0;
}