问题描述:
While exploring his many farms, Farmer John has discovered a number of amazing wormholes. A wormhole is very peculiar because it is a one-way path that delivers you to its destination at a time that is BEFORE you entered the wormhole! Each of FJ’s farms comprises N (1 ≤ N ≤ 500) fields conveniently numbered 1..N, M (1 ≤ M ≤ 2500) paths, and W (1 ≤ W ≤ 200) wormholes.
As FJ is an avid time-traveling fan, he wants to do the following: start at some field, travel through some paths and wormholes, and return to the starting field a time before his initial departure. Perhaps he will be able to meet himself :) .
To help FJ find out whether this is possible or not, he will supply you with complete maps to F (1 ≤ F ≤ 5) of his farms. No paths will take longer than 10,000 seconds to travel and no wormhole can bring FJ back in time by more than 10,000 seconds.
AC代码:
int f[510][510];
int n,m,w;
inline bool floyd()
{
for(int k = 1; k <= n; ++k)
{
for(int i = 1; i <= n; ++i)
{
for(int j = 1; j <= n; ++j)
{
//f[i][j] = min(f[i][j],f[i][k] + f[k][j]);//超时
int d = f[i][k] + f[k][j];
if(f[i][j] > d)
f[i][j] = d;
}
if(f[i][i] < 0)
return true;
}
}
// for(int i = 1; i <= n; ++i)//超时
// if(f[i][i] < 0)
// return true;
return false;
}
int main()
{
int t;
cin >> t;
while(t--)
{
int a,b,c;
scanf("%d%d%d",&n,&m,&w);
memset(f,0x3F,sizeof(f));//初始化邻接矩阵
for(int i = 1; i <= n; ++i)//初始化邻接矩阵
f[i][i] = 0;
for(int i = 1; i <= m; ++i)
{
scanf("%d%d%d",&a,&b,&c);
if(f[a][b] > c)//取较小值
{
f[a][b] = c;
f[b][a] = c;
}
}
for(int i = 1; i <= w; ++i)
{
scanf("%d%d%d",&a,&b,&c);
f[a][b] = -c;//直接覆盖
}
if(floyd() == true)
puts("YES");
else
puts("NO");
}
return 0;
}
解决方法:
正常的道路花费时间,虫洞穿越时间。题目要求农夫从某一农场出发,经过若干农场后再回到该农场,时光发生倒流。题目需要判断负环的存在性。我们求出各农场自回路的最短路径,若其为负,则负环存在。因为要求的是最短路,与虫洞同向的边没有存在的必要。
min函数稍微慢了点,会被卡。
注意在Floyd中,k是阶段,所以必须置于外层循环中,i和j是附加状态,所以应置于内层循环。