POJ

题意:给F个农场(样例),在第一行输入N,M,W(编号范围,路径数,虫洞数)
在2~M+1 行给出从a到b的双向路径,cost为w ; 在M+2~M+n-1 给出从a到b 减时的-w
问从原点出发,能否经过某些路径使得时间回到出发之前(存在负环路)
思路:从题意可知,这就是求图中是否有负环回路问题
那么我们可以想到用bellman-ford算法(spfa)来,
或者我们使用弗洛伊德(简单暴力),只要最后跑出来有dist[i][i]<0 即成立(但是要注意时间复杂度)

...写spfa wa了半天,换floyd 居然就暴力过了..后面还是要spfa也写好

完整代码:

#include<iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue> 
const long long inf=0x3f3f3f3f;
const int maxn=505;
const int maxm=2500;  
using namespace std;
int n,m,s,top;
int g[maxn][maxn];
void addadge(int f,int t,int w){
    g[f][t] = w;
}
int floyd(){
    for(int i = 1;i<=n;i++)
        for(int k = 1;k<=n;k++){
            for(int j=1;j<=n;j++){
                int tmp = g[k][i]+g[i][j];
                if(g[k][j]>tmp) g[k][j]=tmp;
            }
            if(g[k][k]<0) return 0;
        }
    return 1;        
}
void init(){
    memset(g,inf,sizeof(g));
    for(int i=1;i<=n;i++) g[i][i] = 0;
}
int main()
{
    int T;
    cin>>T;
    while(T--){
        init(); 
        cin>>n>>m>>s;
        for(int i=1; i<=m; i++)
        {
            int f,t,w;
            cin>>f>>t>>w; 
            if(w<g[f][t])    g[f][t]=g[t][f]=w;
        }
        for(int i=1; i<=s; i++){
            int f,t,w;
            cin>>f>>t>>w;
            g[f][t]= -w;
        } 
        int ans = floyd();
        if(ans) cout<<"NO"<<endl;
        else cout<<"YES"<<endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/Tianwell/p/11287491.html