题意:给出n个点的m条约束信息。每条信息表述为(P a b c)表示a在b北方距离c的位置,或者(V a b) 表示a在b北方1单位距离或者更远的位置。问是否可能存在符合以上m个要求的点。
思路:差分约束建图,判断可行性可以建立一个虚拟节点,连到所有点的距离为0.道理是这样做可以判断系统中是否存在负环。
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
const int maxn = 1005;
const int maxm = 500005;
int tot,ver[maxm],he[maxn],ne[maxm],cost[maxm];
void add( int x,int y,int c ){
ver[++tot] = y;
ne[tot] = he[x];
he[x] = tot;
cost[tot] = c;
}
int d[maxn],cnt[maxn];
int v[maxn];
queue<int> que;
bool spfa(int s,int n){
memset( d,0x3f,sizeof(int)*(n+1) );
memset(v ,0,sizeof(int)*(n+1) );
cnt[s] = 0;d[s] = 0;v[s] = 1;
while(que.size()) que.pop();
que.push(s);
while( que.size() ){
int x = que.front();que.pop();
v[x] = 0;
for( int cure = he[x];cure;cure = ne[cure] ){
int y = ver[cure],c = cost[cure];
if( d[y] > d[x] + c ){
d[y] = d[x] + c;
cnt[y] = cnt[x] + 1;
if( cnt[y] >= n ) return false;
if(!v[y]){
que.push(y);
v[y] = 1;
}
}
}
}
return true;
}
void init(int n){
memset( he,0,sizeof(int)*(n+1) );
tot = 1;
}
int main(){
int n,m;
char str[10];
while( 2 == scanf("%d%d",&n,&m)){
init(n+1);
int a,b,c;
for( int i = 1;i <= m;i++ ){
scanf("%s%d%d",str,&a,&b);
if( str[0] == 'V' ){
add( a,b,-1 );
}else{
scanf("%d",&c);
add( a,b,-c );
add( b,a,c );
}
}
for( int i = 1;i <= n;i++ ){
add( 0,i,0 );
}
bool flag = spfa( 0,n+1 );
if(flag){
puts("Reliable");
}else{
puts("Unreliable");
}
}
return 0;
}