poj 3259 Wormholes 判断负权回路

       这题没啥好说的,题目看了很久,才明白,原来是虫洞。用判断是否存在负权环,用bellman_ford即可

 

#include<iostream>

using namespace std;



const int MAX = 6000;

const int INF = 1000000000;



struct edge

{

	int u,v;

	int cost;

};



edge e[MAX];



int arcs[505][505];

int n,m,w;

int d[MAX];

int count;



bool bellman_ford()

{

	int u,v,w;

	bool isfinish;

	for (int i = 0; i <= n; i++)

		d[i] = INF;



	d[1] = 0;

	for (int i = 1; i <= n; i++)

	{

		isfinish = true;

		for (int j = 0; j < count; j++)

		{

			u = e[j].u;

			v = e[j].v;

			w = e[j].cost;

			if (d[v] > d[u] + w)

			{

				d[v] = d[u] + w;

				isfinish = false;

			}

		}



		if (isfinish)  break;

	}



	for (int j = 0; j < count; j++)

	{

		u = e[j].u;

		v = e[j].v;

		w = e[j].cost;

		if (d[v] > d[u] + w)

			return false;

	}



	return true;

};



int main()

{

	int cases;

	int a, b, c;



	cin >> cases;



	while (cases--)

	{

		scanf("%d%d%d", &n, &m, &w);



		for (int i = 1; i <= n; i++)

			for (int j = 1; j <= n; j++)

				arcs[i][j] = INF;



		for (int i = 0; i < m; i++)

		{

			scanf("%d%d%d", &a, &b, &c);

			arcs[a][b] = min(arcs[a][b], c);

			arcs[b][a] = arcs[a][b];

		}



		for (int i = 0; i < w; i++)

		{

			scanf("%d%d%d", &a, &b, &c);

			c = -c;

			arcs[a][b] = min(arcs[a][b], c);

		}



		count = 0;

		for (int i = 1; i <= n; i++)

			for (int j = 1; j <= n; j++)

				if (arcs[i][j] < INF)

				{

					e[count].u = i;

					e[count].v = j;

					e[count++].cost = arcs[i][j];

				}



		if (bellman_ford())

			cout << "NO" << endl;

		else

			cout << "YES" << endl;

	}

	return 0;

}

你可能感兴趣的:(orm)