1. 程式人生 > >POj-3259 Wormholes-Floyd判斷負環

POj-3259 Wormholes-Floyd判斷負環

問題描述:
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是附加狀態,所以應置於內層迴圈。