UVa 558 Wormholes (判负圈+Bellman-Ford算法)

来源:互联网 发布:stm32jlink 烧录软件 编辑:程序博客网 时间:2024/05/21 06:49
#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;}

0 0
原创粉丝点击