D - Silver Cow Party
作者:互联网
D - Silver Cow Party
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.
#include <stdio.h>
#include <queue>
#include <math.h>
#include <algorithm>
#include <memory.h>
#define INF 0x3f3f3f3f
#define ll long long
using namespace std;
struct node
{
int w,to,next;
} edge1[100001],edge2[100001];
int head1[1001],head2[1001],cnt,x;
void add(node edge[],int head[],int u,int v,int w)
{
edge[cnt].to=v;
edge[cnt].w=w;
edge[cnt].next=head[u];
head[u]=cnt++;
}
void spfa(node edge[],int head[],int dis[])
{
int u,v,i;
int vis[1001];
memset(vis,0,sizeof(vis));
queue<int>quee;
quee.push(x);
vis[x]=1;
dis[x]=0;
while(!quee.empty())
{
u=quee.front();
quee.pop();
vis[u]=0;
for(i=head[u]; i!=-1; i=edge[i].next)
{
v=edge[i].to;
if(dis[v]>dis[u]+edge[i].w)
{
dis[v]=dis[u]+edge[i].w;
if(!vis[v])
{
quee.push(v);
vis[v]=1;
}
}
}
}
}
int main()
{
int n,m,u[100001],v[100001],w[100001],i,ma,sum;
scanf("%d%d%d",&n,&m,&x);
cnt=0;
memset(head1,-1,sizeof(head1));
memset(head2,-1,sizeof(head2));
for(i=0; i<m; i++)
{
scanf("%d%d%d",&u[i],&v[i],&w[i]);
add(edge1,head1,v[i],u[i],w[i]);//将图反过来存即得 x到任一点的距离
}
int dis1[1001];
memset(dis1,INF,sizeof(dis1));
spfa(edge1,head1,dis1);
cnt=0;
for(i=0; i<m; i++)
{
add(edge2,head2,u[i],v[i],w[i]);//正向图x到任一点的距离
}
int dis2[1001];
memset(dis2,INF,sizeof(dis2));
spfa(edge2,head2,dis2);
ma=0;
for(i=1; i<=n; i++)
{
if(dis1[i]<INF&&dis2[i]<INF)
{
sum=dis1[i]+dis2[i];
ma=max(ma,sum);
}
}
printf("%d\n",ma);
return 0;
}
标签:cow,Cow,int,vis,edge,party,Party,Silver,dis 来源: https://blog.csdn.net/weixin_44040169/article/details/99717916