【洛谷 1821】银牛派对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?
寒假到了,N头牛都要去参加一场在编号为X(1≤X≤N)的牛的农场举行的派对(1≤N≤1000),农场之间有M(1≤M≤100000)条有向路,每条路长Ti(1≤Ti≤100)。
每头牛参加完派对后都必须回家,无论是去参加派对还是回家,每头牛都会选择最短路径,求这N头牛的最短路径(一个来回)中最长的一条路径长度。
输入输出格式
输入格式:
第一行三个整数N,M, X;
第二行到第M+1行:每行有三个整数Ai,Bi, Ti ,表示有一条从Ai农场到Bi农场的道路,长度为Ti。
输出格式:
一个整数,表示最长的最短路得长度。
输入输出样例
说明
题解:正反两个方向建图,跑两遍SPFA即可。
#include<cstdio> #include<iostream> #include<cmath> #include<cstdlib> #include<cstring> #include<algorithm> #include<queue> using namespace std; const int oo=0x3f3f3f3f; int n,m,x,y,z,kun; int d1[100005],vis[100005]; int d2[100005]; struct node{ int to; int next; int val; }e1[100005]; node e2[100005]; int h1[100005]; int h2[100005]; int cnt1,cnt2; void add(int a,int b,int c){ cnt1++; e1[cnt1].to=b; e1[cnt1].val=c; e1[cnt1].next=h1[a]; h1[a]=cnt1; cnt2++; e2[cnt2].to=a; e2[cnt2].val=c; e2[cnt2].next=h2[b]; h2[b]=cnt2; } void cai(){ queue<int>q; memset(vis,0,sizeof(vis)); //memset(q,0,sizeof(q)); q.push(kun); d1[kun]=0; vis[kun]=1; while(!q.empty()){ x=q.front(); q.pop(); vis[x]=0; for(int i=h1[x];i;i=e1[i].next){ int v=e1[i].to; if(d1[v]>d1[x]+e1[i].val){ d1[v]=d1[x]+e1[i].val; if(vis[v]==0){ q.push(v); vis[v]=1; } } } } } void xu(){ queue<int>q; memset(vis,0,sizeof(vis)); //memset(q,0,sizeof(q)); q.push(kun); d2[kun]=0; vis[kun]=1; while(!q.empty()){ x=q.front(); q.pop(); vis[x]=0; for(int i=h2[x];i;i=e2[i].next){ int v=e2[i].to; if(d2[v]>d2[x]+e2[i].val){ d2[v]=d2[x]+e2[i].val; if(vis[v]==0){ q.push(v); vis[v]=1; } } } } } int main(){ freopen("1821.in","r",stdin); freopen("1821.out","w",stdout); scanf("%d %d %d",&n,&m,&kun); for(int i=1;i<=m;i++){ scanf("%d %d %d",&x,&y,&z); add(x,y,z); } for(int i=1;i<=n;i++) d1[i]=d2[i]=oo; cai(); xu(); int ans=0; for(int i=1;i<=n;i++) ans=max(ans,d1[i]+d2[i]); printf("%d",ans); /*int mx=0; int id=0; for(int i=1;i<=n;i++) if(d2[i]>mx) { mx=d2[i]; id=i; } printf("%d %d ",id,mx); int ans=0; for(int i=1;i<=n;i++) ans+=(mx==d2[i]); printf("%d",ans);*/ return 0; }