POJ-3259 Wormholes(最短路,bellman求负环)

原题:点击打开链接

题意:

在n个结点之中,有权值为正的无向路,也有权值为负的有向虫洞,问能不能从起点返回起点之后所用时间为负值。

思路:

明显题目意思就是让求图中有没有负环,有负环则能满足题意。于是用bellman法判断负环存不存在就可以了。

代码:

<pre class="sh_cpp sh_sourceCode" style="font-size:14px; font-family: 'Courier New', Courier, monospace; background-color: white;"><pre name="code" class="cpp">#include <iostream>
#include<string.h>
using namespace std;

struct node
{
	int a, b, t;
}path[5300];

int n, m, W, tol;
int dis[510];
const int inf = 0x3f3f3f3f;
bool ford()
{
	for(int i = 0;i <= n;i++)
		dis[i] = inf;
	for(int i = 0;i < n-1;i++)
	{
		bool flag = false;
		for(int j = 0;j < tol;j++)
			if(dis[path[j].b] > dis[path[j].a] + path[j].t)
				dis[path[j].b] = dis[path[j].a] + path[j].t, flag = true;
		if(!flag)
			break;
	}
	for(int i = 0;i <tol;i++)
		if(dis[path[i].b] > dis[path[i].a] + path[i].t)
			return true;
	return false;
}

int main()
{
    int F;
    cin>>F;
    while(F--)
	{
		cin>>n>>m>>W;
		tol = 0;
		int u, v, w;
		for(int i = 0;i < m;i++)
		{
			cin>>u>>v>>w;
			path[tol].a = u;
			path[tol].b = v;
			path[tol++].t = w;
			path[tol].a = v;
			path[tol].b = u;
			path[tol++].t = w;
		}
		for(int i = 0;i < W;i++)
		{
			int temp;
			cin>>path[tol].a>>path[tol].b>>temp;
			path[tol++].t = -temp;
		}
		if(ford())
			cout<<"YES"<<endl;
		else
			cout<<"NO"<<endl;
	}
    return 0;
}


 
 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值