Bellman_Ford算法 求图中是否存在负权值的回路 若图中不存在 则最短路最多经过n-1个结点 若经过超过n-1个节点 则存在负权值的回路 此图永远无法找到最短路 每条边最多经过n-1次松弛~~
#include<cstdio>
#include<cstring>
#include<queue>
#include<vector>
using namespace std;
const int INF = 100000000;
const int maxn = 1005;
vector<int> G[maxn];
int weight[maxn][maxn];
queue<int> q;
bool inq[maxn];
int d[maxn],vis[maxn];
int n,m;
bool Bellman_Ford()
{
for(int i = 0 ; i < n; i++) d[i] = INF,inq[i] = false;
d[0] = 0;
memset(vis, 0, sizeof(vis));
q.push(0);
inq[0] = true;
while(!q.empty())
{
int u = q.front();
q.pop();
inq[u] = false;
for(int i = 0; i < (int)G[u].size(); i++)
{
int v = G[u][i];
if(d[v] > d[u] + weight[u][v])
{
d[v] = d[u] + weight[u][v];
if(!inq[v])
{
inq[v] = true;
vis[v++];
if(vis[u] >= n) return true;
q.push(v);
}
}
}
}
return false;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
for(int i = 0; i < n; i++) G[i].clear();
for(int i = 0 ; i < m; i++)
{
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
G[u].push_back(v);
weight[u][v] = w;
}
if(Bellman_Ford()) puts("possible");
else puts("not possible");
}
return 0;
}
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<queue>
#include<algorithm>
using namespace std;
const int N = 2005;
const int INF = 0xffffff;
struct Edge
{
int u,v,w;
} edge[N];
int n,m;
int d[N];
bool Bellman_Ford()
{
for(int i = 0; i < n; i++) d[i] = INF;
d[0] = 0;
bool flag;
for(int i = 0; i < n; i++)
{
flag=false;
for(int j = 0; j < m; j++)
{
if(d[edge[j].v] > d[edge[j].u]+edge[j].w)
{
d[edge[j].v] = d[edge[j].u]+edge[j].w;
flag=true;
}
}
if(!flag)
break;
}
for(int j = 0; j < m; j++)
if(d[edge[j].v] > d[edge[j].u]+edge[j].w)
return true;
return false;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
memset(edge,0,sizeof(edge));
scanf("%d%d",&n,&m);
for(int i = 0; i < m; i++)
scanf("%d%d%d",&edge[i].u,&edge[i].v,&edge[i].w);
if(Bellman_Ford())
puts("possible");
else
puts("not possible");
}
return 0;
}