码迷,mamicode.com
首页 > 其他好文 > 详细

POJ 2983 Is the Information Reliable?

时间:2015-01-31 11:55:59      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:

 

/*
*POJ 2983 Is the Information Reliable?
*差分约束系统
*(1)对于确定信息 P A B X, 有 A - B >= X && A - B <= X 即 B <= A + (-X) && A <= B + X
*	即构成边<A, B, -X> 和 <B, A, X>
*(2)对于不确定信息 V A B, 有 A - B >= 1, 即 B <= A + (-1)
*	即构成边 <A, B, -1>
*由于可能存在孤立点,需要加入超级源点 0, 构造 <0, Vi, 0> (i: [1,n] )
*最终判定若有负值回路则输出 “Unreliable”
*否则 “Reliable”
*/
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>

using namespace std;

const int INF = 0x3f3f3f3f;
const int MAXN = 1010;

struct ArcNode {
	int to, w;
	ArcNode *next;
};

int n, m;
ArcNode *List[MAXN];
bool visit[MAXN];
int dist[MAXN];
int cont[MAXN];

bool spfa(int src)
{
	queue<int > Q;
	int i, u, v;
	ArcNode *temp;
	memset(dist, INF, sizeof(dist));
	memset(visit, false, sizeof(visit));
	memset(cont, 0, sizeof(cont));
	dist[src] = 0;
	Q.push(src);
	cont[src] ++;
	while (Q.size()) {
		u = Q.front();
		visit[u] = 0;
		Q.pop();
		temp = List[u];
		while (temp != NULL) {
			v = temp->to;
			if (dist[v] > dist[u] + temp->w) {
				dist[v] = dist[u] + temp->w;
				if (!visit[v]) {
					visit[v] = 1;
					cont[v] ++;
					if (cont[v] > n) {
						return false;
					}
					Q.push(v);
				}
			}
			temp = temp->next;
		}

	}
	return true;
}

int main()
{
	int i;
	int u, v, w;
	char s[5];
	while (~scanf("%d %d", &n, &m)) {
		memset(List, 0, sizeof(List));
		ArcNode *temp;
		for (i = 1; i <= n; i++) {
			temp = new ArcNode;
			temp->to = i;   temp->w = 0;    temp->next = NULL;
			if (List[0] == NULL) {
				List[0] = temp;
			} else {
				temp->next = List[0];   List[0] = temp;
			}
		}
		for (i = 0; i < m; i++) {
			scanf("%s", s);
			if (s[0] == ‘P‘) {
				scanf("%d %d %d", &u, &v, &w);
				temp = new ArcNode;
				temp->to = v;   temp->w = -w;   temp->next = NULL;
				if (List[u] == NULL) {
					List[u] = temp;
				} else {
					temp->next = List[u];   List[u] = temp;
				}
				temp = new ArcNode;
				temp->to = u;   temp->w = w;    temp->next = NULL;
				if (List[v] == NULL) {
					List[v] = temp;
				} else {
					temp->next = List[v];   List[v] = temp;
				}
			}
			if (s[0] == ‘V‘) {
				scanf("%d %d", &u, &v);
				temp = new ArcNode;
				temp->to = v;   temp->w = -1;    temp->next = NULL;
				if (List[u] == NULL) {
					List[u] = temp;
				} else {
					temp->next = List[u];   List[u] = temp;
				}
			}
		}
		if (spfa(0)) {
			printf("Reliable\n");
		} else {
			printf("Unreliable\n");
		}
	}
}

  

POJ 2983 Is the Information Reliable?

标签:

原文地址:http://www.cnblogs.com/subrshk/p/4263786.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!