Silver Cow Party
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 16352 | Accepted: 7474 |
Description
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.
题意:一群牛分别从1~n号农场赶往x号农场参加聚会,农场与农场之间的路时单向的,在n个农场之间有m条路,给出 a ,b , t表示从a号农场到b号农场需要t时间。 每头牛都会选择最短的路,问来回路上(i→x+x→i)花费时间最长的牛花费的时间是多少?
题解:一眼看过去很简单,先计算x农场到其他农场用的最短时间,在枚举其他农场到x农场的最短时间,记录下最大来回时间即可。的确,不过我们算一算时间复杂度,在枚举其他农场到x农场的最短时间时,最大复杂度为O(n^3)。也就是1000^3,很明显超过了2000ms。所以我们要想办法把枚举过程的复杂度降下来。 这里可以采用置换矩阵,因为是路径时单向的,我们交换 map[i][j] 与 map[j][i] 的值,那么枚举过程就变成了求x到其他农场的最短时间,这里就变成了O(n^2)的算法。
代码如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define INF 0x3f3f3f3f
#define maxn 1010
int map[maxn][maxn],n;
int way[maxn],dis[maxn];
void dijkstra(int x)
{
int visit[maxn],i,j,min,next=x;
memset(visit,0,sizeof(visit));
for(i=1;i<=n;++i)
dis[i]=map[x][i];
visit[x]=1;
for(i=2;i<=n;++i)
{
min=INF;
for(j=1;j<=n;++j)
{
if(!visit[j]&&dis[j]<min)
{
min=dis[j];
next=j;
}
}
visit[next]=1;
for(j=1;j<=n;++j)
{
if(!visit[j]&&dis[j]>dis[next]+map[next][j])
dis[j]=dis[next]+map[next][j];
}
}
}
int main()
{
int m,x,i,j,a,b,t;
while(scanf("%d%d%d",&n,&m,&x)!=EOF)
{
for(i=1;i<=n;++i)
{
for(j=1;j<=n;++j)
{
if(i!=j)
map[i][j]=INF;
else
map[i][j]=0;
}
}
while(m--)
{
scanf("%d%d%d",&a,&b,&t);
if(t<map[a][b])
map[a][b]=t;
}
dijkstra(x);
for(i=1;i<=n;++i)
way[i]=dis[i];
int ans=0;
for(i=1;i<=n;++i)//置换矩阵的值,也就是交换map[i][j]与map[j][i]的值
{
for(j=i+1;j<=n;++j)
{
int cnt;
cnt=map[j][i];
map[j][i]=map[i][j];
map[i][j]=cnt;
}
}
dijkstra(x);
for(i=1;i<=n;++i)
{
if(i!=x)
ans=max(ans,way[i]+dis[i]);
}
printf("%d\n",ans);
}
return 0;
}