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

本文介绍了一种使用Bellman-Ford算法检测带负权重边的图中是否存在负权重环的方法,并提供了完整的C++实现代码。该算法适用于解决最短路径问题,在存在负权重边的情况下也能正确工作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值