poj 3259 wormholes AC代码(负权环判断, Bellmanford)

12 篇文章 0 订阅
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
#include<iomanip>
#include<cstdlib>
#include<cstdio>
#include<vector>
#include<algorithm>
#include<cmath>
#include<map>

using namespace std;

const int INF = 10001;

struct Edge {
	int from;
	int to;
	int wgt;
	Edge(int f = -1, int t = -1, int w = INF) :
		from(f), to(t), wgt(w){}
};

bool bellmanford(vector<Edge> &G, int num, int src) {
	vector<int> dist(num+1, INF);
	dist[src] = 0;

	int st;
	for (st = 0; st < num; ++st) {
		bool chg = false;
		for (int i = 0; i < G.size(); ++i) {
			if (dist[G[i].to] > dist[G[i].from] + G[i].wgt) {
				dist[G[i].to] = dist[G[i].from] + G[i].wgt;
				chg = true;
			}
		}
		if (!chg) break;
	}

	if (st == num) return true;
	else return false;
}

int main(void)
{
	int F;
	cin >> F;
	while (F--) {
		int N, M, W;
		cin >> N >> M >> W;

		vector<Edge> G;

		for (int i = 0; i < M; ++i) {
			int s, e, t;
			scanf("%d%d%d", &s, &e, &t);
			G.push_back(Edge(s, e, t));
			G.push_back(Edge(e, s, t));
		}

		for (int i = 0; i < W; ++i) {
			int s, e, t;
			scanf("%d%d%d", &s, &e, &t);
			G.push_back(Edge(s, e, -t));
		}

		if (bellmanford(G, N, 1))
			cout << "YES" << endl;
		else
			cout << "NO" << endl;
	}
	
	//system("pause");
	return 0;

}
如果用STL做邻接矩阵的话会超时,内存申请释放开销太大.而且题目中<span style="font-family: 'Times New Roman', Times, serif; font-size: 16px;">N</span><span style="font-family: 'Times New Roman', Times, serif; font-size: 16px;"> (1 ≤ </span><span style="font-family: 'Times New Roman', Times, serif; font-size: 16px;">N</span><span style="font-family: 'Times New Roman', Times, serif; font-size: 16px;"> ≤ 500), <span style="font-family: 'Times New Roman', Times, serif; font-size: 16px;">M</span><span style="font-family: 'Times New Roman', Times, serif; font-size: 16px;"> (1 ≤ </span><span style="font-family: 'Times New Roman', Times, serif; font-size: 16px;">M</span><span style="font-family: 'Times New Roman', Times, serif; font-size: 16px;"> ≤ 2500), <span style="font-family: 'Times New Roman', Times, serif; font-size: 16px;">W</span><span style="font-family: 'Times New Roman', Times, serif; font-size: 16px;"> (1 ≤ </span><span style="font-family: 'Times New Roman', Times, serif; font-size: 16px;">W</span><span style="font-family: 'Times New Roman', Times, serif; font-size: 16px;"> ≤ 200) 明显为稀疏图,如果用邻接矩阵表示的话,搜索的开销也会很大.于是考虑储存边的信息.</span></span></span>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值