这里也要建立<=差分约束系统,判断消息是否可靠看的是建立的图是否存在负圈。
如存在则不可靠,不存在则可靠。
建立<=的差分系统:
由于P A B X 指“确定A到B的距离(边权)为X”
从P A B X得到的差分系统为
dist[A] - dist[B] >= X && dist[A] - dist[B] <= X
等价于
dist[B] <= dist[A] - X && dist[A] <= dist[B] + X
则if(dist[B] > dist[A]-X) 松弛:dist[B] = dist[A]-X
由于 V A B指“只知道A到B的距离(边权)至少为1”
从V A B得到的差分系统为
dist[A] >= dist[B] +1
等价于
dist[B] <= dist[A] -1
则if(dist[B] > dist[A] -1)
松弛:dist[B] = dist[A] -1
摘自 http://blog.csdn.net/lyy289065406/article/details/6648688
/*Accepted 2472K 454MS C++ 1260B 2012-08-06 12:44:54*/ #include<stdio.h> #include<string.h> #include<stdlib.h> const int MAXN = 1010, MAXM = 100010; int u[MAXM * 2], v[MAXM * 2], w[MAXM * 2], dist[MAXN]; int n, m, e; void addedge(int a, int b, int c) { u[e] = a, v[e] = b, w[e ++] = c; } void ReadGraph() { int i, a, b, c; char op[5]; e = 0; memset(dist, 0, sizeof dist); for(i = 0; i < m; i ++) { scanf("%s", op); if('P' == op[0]) { scanf("%d%d%d", &a, &b, &c); addedge(a, b, -c), addedge(b, a, c); } else { scanf("%d%d", &a, &b); addedge(a, b, -1); } } } void BellmanFord() { int i, j; bool flag; for(i = 0; i < n; i ++) //n轮迭代 { flag = false; for(j = 0; j < e; j ++) { if(dist[v[j]] > dist[u[j]] + w[j]) { dist[v[j]] = dist[u[j]] + w[j]; flag = true; } } if(!flag) break; //这里是优化 } if(flag) //超过N - 1轮迭代就存在负圈,这里将无限迭代下去 printf("Unreliable\n"); else printf("Reliable\n"); } int main() { while(scanf("%d%d", &n, &m) == 2) { ReadGraph(); BellmanFord(); } return 0; }