标签:
/* *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