poj2983 差分约束判断是否可行(图不一定连通)

题意:给出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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值