#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<iostream>
#include<queue>
#include<vector>
#include<set>
#include<climits>
#include<map>
#include<string>
using namespace std;
const int INF=100000000;
const int maxn=1000+10;
const int maxm=2000+10;
int n,m;
int first[maxn];
int d[maxn];
int u[maxm],v[maxm],w[maxm],nnext[maxm];
int V;
//稀疏图的邻接表
void read_graph()
{
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++)first[i]=-1;
for(int e=0;e<m;e++)
{
scanf("%d%d%d",&u[e],&v[e],&w[e]);
nnext[e]=first[u[e]];
first[u[e]]=e;
}
}
//Bellman-Ford算法
bool Bellman_Ford()
{
queue<int> q;
bool inq[maxn];
for(int i=0;i<n;i++)
d[i]=(i==0 ? 0:INF);
V=0;
memset(inq,0,sizeof(inq));
q.push(0);
while(!q.empty())
{
int x=q.front();
q.pop();
inq[x]=false;
for(int e=first[x];e!=-1;e=nnext[e])if(d[v[e]]>d[x]+w[e])
{
d[v[e]]=d[x]+w[e];
V++;
if(V==n)return true; //更新次数超过n-1次,有负圈
if(!inq[v[e]])
{
inq[v[e]]=true;
q.push(v[e]);
}
}
}
return false;
}
int main()
{
int c;
scanf("%d",&c);
while(c--)
{
read_graph();
if(Bellman_Ford())printf("possible\n");
else printf("not possible\n");
}
return 0;
}
UVa 558 Wormholes (判负圈+Bellman-Ford算法)
最新推荐文章于 2019-10-22 17:02:01 发布