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。
输出格式:
一个整数,表示最长的最短路得长度。
输入样例#1: 复制
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
输出样例#1: 复制
10
题解
单源最短路+单终点最短路,单终点反着存一遍边就好
code
#include
#include
#include
#include
#include
#include
using namespace std;
const int M=100005;
int n,m,x,adj1[M],adj2[M],head1[M],head2[M],next1[M],next2[M],W1[M],W2[M],k,d1[M],d2[M];
void addedge1(int u,int v,int w)
{
next1[++k]=head1[u];
head1[u]=k;
W1[k]=w;
adj1[k]=v;
}
void addedge2(int u,int v,int w)
{
next2[++k]=head2[u];
head2[u]=k;
W2[k]=w;
adj2[k]=v;
}
int main()
{
int a,b,t,i,j,K;
scanf("%d%d%d",&n,&m,&x);
for(i=1;i<=m;i++)
{
scanf("%d%d%d",&a,&b,&t);
addedge1(a,b,t);
addedge2(b,a,t);
}
bool flag=true;
memset(d1,0x7f,sizeof(d1));
memset(d2,0x7f,sizeof(d2));
d1[x]=0;
d2[x]=0;
for(i=1;i<=n-1;i++)
{
if(!flag)break;
flag=false;
for(j=1;j<=n;j++)
{
for(K=head1[j];K;K=next1[K])
if(d1[adj1[K]]>d1[j]+W1[K])
{
d1[adj1[K]]=d1[j]+W1[K];
flag=true;
}
for(K=head2[j];K;K=next2[K])
if(d2[adj2[K]]>d2[j]+W2[K])
{
d2[adj2[K]]=d2[j]+W2[K];
flag=true;
}
}
}
int ans=0;
for(i=1;i<=n;i++)
{
if(d1[i]+d2[i]>ans)
ans=d1[i]+d2[i];
}
printf("%d\n",ans);
return 0;
}
ps.话说这道题宋奶牛讲了很长时间啊,竟然没有在毕业典礼上合影,遗憾啊。