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

差分约束系统

构图

A=B+x  =>  A-B>=x && A-B<=X

 

A>=B+1

判断负环

因为只需要判断是否存在负环,所以无需添加超级源点。直接把所有节点的dist属性初始化为0。

#include <iostream> using namespace std; struct Edge { int x,y,dist; }edges[200005]; int edge_num,N,M; int dist_array[1005]; void AddEdge(int x,int y,int dist) { edges[edge_num].x=x; edges[edge_num].y=y; edges[edge_num].dist=dist; edge_num++; } bool Bellman_Ford() { bool change; for(int i=0;i<N;i++) { change=false; for(int j=0;j<edge_num;j++) { if(dist_array[edges[j].x]+edges[j].dist<dist_array[edges[j].y]) { dist_array[edges[j].y]=dist_array[edges[j].x]+edges[j].dist; change=true; } } } return !change; } int main() { while(scanf("%d%d",&N,&M)!=EOF) { memset(dist_array,0,sizeof(dist_array)); edge_num=0; int x,y,dist; char flag; for(int i=0;i<M;i++) { scanf("/n%c%d%d",&flag,&x,&y); if(flag=='P') { scanf("%d",&dist); AddEdge(x,y,-dist); AddEdge(y,x,dist); } else { AddEdge(x,y,-1); } } if(Bellman_Ford()) printf("Reliable/n"); else printf("Unreliable/n"); } return 0; }

 

你可能感兴趣的:(pku 2983 Is the Information Reliable?(差分约束系统))