您的位置:首页 > 编程语言

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

2015-06-17 14:34 267 查看
#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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: