POJ 2983 Is the Information Reliable?(差分约束系统)

题目链接

题意

P A B X表示A在B点的北边的准确距离为X

V A B表示A在B的北边,但是具体的距离不确定,但是距离一定大于1.

询问是否存在一种情况使N个据点满足之前的条件。

思路

两个点的距离确定是x,相当于

a - b >= x
&&
a - b <= x

另外一个条件就是

a - b >= 1

通过这两个信息建边,可以求最短路也可以最长路,区别就是,最短路判断负环,最长路判断正环

PS:

坑死我了,边最多是20w + 1000个,我数组开小了,我开了11w,它提示我TLE,服了

CODE

#include <queue>
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
#pragma warning (disable:4996)
#pragma warning (disable:6031)
#define mem(a, b) memset(a, b, sizeof a)
using namespace std;
const int N = 220000;
int head[N], nex[N], to[N], edge[N], cnt, _cnt[N], d[N];
bool v[N];
int n, m;
struct SPFA {
	SPFA() {
		mem(head, -1);
		mem(nex, -1);
		mem(_cnt, 0);
		mem(d, 0x3f);
		mem(v, false);
		cnt = 0;
	}
	void init() {
		SPFA();
	}
	void add(int a, int b, int c) {
		++cnt;
		to[cnt] = b;
		edge[cnt] = c;
		nex[cnt] = head[a];
		head[a] = cnt;
	}
	bool spfa() {
		queue<int> q;
		q.push(0);
		d[0] = 0;
		v[0] = 1;
		_cnt[0]++;
		while (!q.empty()) {
			int t = q.front();
			q.pop();
			v[t] = 0;
			for (int i = head[t]; i != -1; i = nex[i]) {
				int y = to[i];
				int dist = edge[i];
				if (d[y] > d[t] + dist) {
					d[y] = d[t] + dist;
					if (!v[y]) {
						v[y] = 1;
						q.push(y);
						_cnt[y]++;
						if (_cnt[y] > n) {
							return false;
						}
					}
				}
			}
		}
		return true;
	}
};
int main()
{
	SPFA sp;
	while (~scanf("%d %d", &n, &m)) {
		sp.init();
		int a, b, c;
		char ch;
		for (int i = 0; i < m; i++) {
			getchar();
			ch = getchar();
			if (ch == 'V') {
				scanf("%d %d", &a, &b);
				sp.add(a, b, -1);
			}
			else {
				scanf("%d %d %d", &a, &b, &c);
				sp.add(b, a, c);
				sp.add(a, b, -c);
			}
		}
		for (int i = 1; i <= n; i++) {
			sp.add(0, i, 0);
		}
		if (sp.spfa()) {
			puts("Reliable");
		}
		else {
			puts("Unreliable");
		}
	}
	return 0;
}
发布了143 篇原创文章 · 获赞 11 · 访问量 8184

猜你喜欢

转载自blog.csdn.net/weixin_43701790/article/details/104070476
今日推荐