# UVa 558 Wormholes 判断负权环 对比bellman-ford和spfa效率

``````/**
*   又是大水。。再来测试测试bellman-ford和spfa的效率。。
*   居然。。。bellman-ford比spfa要快好多。。。 求解释？
*   附加floyd判负权环。其实原来和bellman一样。
*/

#include <cstdio>
#include <iostream>
#include <cstring>
#include <cmath>
#include <string>
#include <queue>
#include <map>
#include <vector>
#include <algorithm>
#define DEBUG 0
#define INF 0x1fffffff
#define MAXS 2005

typedef long long LL;
using namespace std;

int u[MAXS], v[MAXS], t[MAXS];
int dis[MAXS], inq[MAXS], times[MAXS];
int n, m;
struct Edge
{
int v, t;
Edge() {}
Edge(int vv, int tt) {v = vv; t = tt;}
};
vector<Edge> ver[MAXS];

int cnt = 0;
bool bellman()
{
for(int i = 0; i < n; i ++) {
dis[i] = INF;
}
dis[0] = 0;
for(int k = 0; k < n - 1; k ++)
for(int i = 0; i < m; i ++)
{
if(dis[u[i]] != INF && dis[v[i]] > dis[u[i]] + t[i])
dis[v[i]] = dis[u[i]] + t[i];
}

for(int i = 0; i < m; i ++)
{
if(dis[u[i]] != INF && dis[v[i]] > dis[u[i]] + t[i])
return true;
}

return false;
}

bool spfa()
{
queue<int> q;
for(int i = 0; i < n; i ++) {
inq[i] = 0;
times[i] = 0;
dis[i] = INF;
}
inq[0] = 1;
dis[0] = 0;
q.push(0);
while(!q.empty())
{
int cur = q.front(); q.pop();
times[cur] ++;
inq[cur] = 0;
if(times[cur] > n) return true;
for(int i = 0; i < ver[cur].size(); i ++)
{
int vv = ver[cur][i].v, tt = ver[cur][i].t;
if(dis[cur] != INF && dis[vv] > dis[cur] + tt)
{
dis[vv] = dis[cur] + tt;
if(!inq[vv]) {
inq[vv] = 1;
q.push(vv);
}
}
}
}
return false;
}

int main()
{
int cases;  scanf("%d", &cases);
while(cases --)
{
scanf("%d%d", &n, &m);
for(int i = 0; i < n; i ++)
ver[i].clear();
for(int i = 0; i < m; i ++) {
int uu, vv, tt;
scanf("%d%d%d", &uu, &vv, &tt);
ver[uu].push_back(Edge(vv, tt));
}
if(spfa()) printf("possible\n");
else printf("not possible\n");
}
return 0;
}

/**
bool floyd()
{
for(int k = 0; k < n; k ++) {
for(int i = 0; i < n; i ++)
{
for(int j = 0; j < n; j ++) {
if(gra[i][j] > gra[i][k] + gra[k][j])
gra[i][j] = gra[i][k] + gra[k][j];
}
}
for(int i = 0; i < n; i ++)
for(int j = 0; j < n; j ++) {
if(gra[i][j] > gra[i][k] + gra[k][j])
return true;
}
}
return false;
}
*/
``````

原文作者：Bellman - ford算法
原文地址: https://blog.csdn.net/xuruoxin/article/details/11835183
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。