POJ - 2983 Is the Information Reliable 【spfa解决差分约束问题】

版权声明:如需转载,记得标识出处 https://blog.csdn.net/godleaf/article/details/88029353

题目链接:http://poj.org/problem?id=2983

原理在上篇博客已经讲过了,这里把要注意的讲下。

1,因为差分约束问题都是不等式约束,以不等式为基础给题目建图,但是如果题目给出的约束条件是 d[u] - d[v] == w,怎么处理?

w <= d[u] - d[v] <= w,这样就能表示d[u] - d[v] == w这个条件,一条正向正权值,一条反向负权值。

2,因为之前的题目做习惯了,习惯性的给点从1到N的顺序依次加一条权值为0的边,让构建出来的图是一个连通图,因为题目的点虽然是直线排列的,但是排列的顺序不是从1到N的,所以要么把顺序记下来,再根据顺序依次加一条权值为0的边,要么就是把所有的点都加到队列里面也是一样的,虽然图不连通,但是点全加到队列里面能保证每一条边都能够松弛得了。

#include <iostream>
#include <queue>
#include <cstring>
#include <string>
#include <map>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>

using namespace std;

#define lson (cur<<1)
#define rson (cur<<1|1)
typedef long long ll;
typedef pair<int, int> pii;

const int INF = 0x3f3f3f3f;
const long long LINF = 1e18;
const int Maxn = 1e5+10;
const int Mod = 1e9+7;

struct Edge {
    int v, w;
    Edge(int x = 0, int y = 0):v(x), w(y) {};
} edge[Maxn*2+1000];

int d[1010], cnt[1010], Hash[Maxn<<1];
vector <int> G[1010];
bool vis[1010];

bool spfa(int E, int n) {
    memset(vis, true, sizeof(vis));
    memset(cnt, 0, sizeof(cnt));
    memset(d, 0, sizeof(d));
    queue<Edge> qu;
    for(int i = 0; i < n; ++i)
        qu.push(Edge(Hash[i], 0));

    while(!qu.empty()) {
        int v = qu.front().v; qu.pop();
        vis[v] = false;

        for(int i = 0; i < G[v].size(); ++i) {
            Edge &e = edge[G[v][i]];
            if(d[e.v] < d[v]+e.w) {
                d[e.v] = d[v]+e.w;
                if(!vis[e.v]) {
                    vis[e.v] = true;
                    cnt[e.v]++;
                    if(cnt[e.v] > E) return false;
                    qu.push(Edge(e.v, d[e.v]));
                }
            }
        }
    }
    return true;
}

int main(void)
{
    int N, M;
    while(scanf("%d%d", &N, &M) != EOF) {
        for(int i = 0; i <= N; ++i) G[i].clear();
        memset(Hash, 0, sizeof(Hash));
        int E = 0, n = 0, u, v, w;
        char ch;
        for(int i = 0; i < M; ++i) {
            scanf(" %c", &ch);
            if(ch == 'P') {
                scanf("%d%d%d", &u, &v, &w);
                edge[E].v = v; edge[E].w = w;
                G[u].push_back(E);
                E++;
                edge[E].v = u; edge[E].w = -w;
                G[v].push_back(E);
                E++;
                Hash[n++] = u; Hash[n++] = v;
            } else {
                scanf("%d%d", &u, &v);
                edge[E].v = v; edge[E].w = 1;
                G[u].push_back(E);
                E++;
                Hash[n++] = u; Hash[n++] = v;
            }
        }
        sort(Hash, Hash+n);
        n = unique(Hash, Hash+n)-Hash;

        if(spfa(E, n)) printf("Reliable\n");
        else printf("Unreliable\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/godleaf/article/details/88029353