题目
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头牛 要从自己所在的位置到x去 再从x位置回到自己所在的位置,问这n头牛中要花费的最长来回时间
思路
一开始,我用五行代码那个算法写的,看着题目给的数据不大,想着不会超时,一直过不去,然后换了一个方法用dijkstra求,我是开了两个数组,一个用来记录每头牛去x的时间,一个记录每头牛从x回来的时间。
最后再遍历一遍数组,把来和回所用的时间加在一起看哪头牛花费的时间最长,求出即可
代码
#include<stdio.h>
#include<string.h>
int e[1010][1010],dis[10100],book[1010],dis1[1010],book1[1010];
#define inf 9999999
int main()
{
int i,j,k,m,n,a,b,c,o,min,u,v;
scanf("%d%d%d",&n,&m,&o);
for(i=1; i<=n; i++)
for(j=1; j<=n; j++)
{
if(i==j)
e[i][j]=0;
else
e[i][j]=inf;
}
for(i=1; i<=m; i++)
{
scanf("%d%d%d",&a,&b,&c);
e[a][b]=c;
}
for(i=1; i<=n; i++)
dis[i]=e[i][o];
memset(book,0,sizeof(book));
book[o]=1;
for(i=1; i<=n; i++)
{
min=inf;
for(j=1; j<=n; j++)
{
if(book[j]==0&&dis[j]<min)
{
u=j;
min=dis[j];
}
}
book[u]=1;
for(int v=1; v<=n; v++)
{
if(e[v][u]+dis[u]<dis[v]&&e[v][u]<inf)
dis[v]=dis[u]+e[v][u];
}
}
int sum=0;
for(i=1; i<=n; i++)
dis1[i]=e[o][i];//huiqudelu
memset(book1,0,sizeof(book1));
book1[o]=1;
for(i=1; i<=n; i++)
{
min=inf;
for(j=1; j<=n; j++)
{
if(book1[j]==0&&dis1[j]<min)
{
min=dis1[j];
u=j;
}
}
book1[u]=1;
for(int v=1; v<=n; v++)
{
if(e[u][v]+dis1[u]<dis1[v]&&e[u][v]<inf)
dis1[v]=dis1[u]+e[u][v];
}
}
sum=-1000;
for(i=1; i<=n; i++)
{
if(dis[i]+dis1[i]>sum)
{
// printf("%d %d\n",dis[i],dis1[i]);
sum=dis[i]+dis1[i];
}
}
printf("%d\n",sum);
return 0;
}
总结
要把时间复杂度尽可能的降低