zoj 1508 | poj 1201 Intervals

類型:差分約束

題目:http://poj.org/problem?id=1201

來源:Southwestern Europe 2002
思路:設S[i]是集合z中小於等於i的元素的個數

(1)z集合中範圍在[ai, bi]的整數個數即S[bi] - S[ai-1]至少爲ci,得到不等式組

S[bi] - S[ai-1] >= ci ,轉化爲 S[ai-1] - S[bi] <= -ci;

(2)S[i] - S[i - 1] <= 1

(3)S[i] - S[i - 1] >= 0 => S[i - 1] - S[i] <= 0

據此構造有向圖,設所有區間右端點最大值爲maxb,左端點最小值爲minb

題目要求的即是S[maxb] - S[minb - 1]的最小值,即求S[maxb] - S[minb - 1] >= M中的M

轉化爲S[minb - 1] - S[maxb] <= -M。即求源點maxb到終點minb - 1的最短路

設最短路徑長保存在dist中,那麼-M = dist[minb - 1] - dist[maxb]

M = dist[maxb] - dist[minb - 1]

#include <iostream>
#include <string>
#include <queue>
#include <stack>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;

#define FOR(i,a,b) for(i = (a); i < (b); ++i)
#define FORE(i,a,b) for(i = (a); i <= (b); ++i)
#define FORD(i,a,b) for(i = (a); i > (b); --i)
#define FORDE(i,a,b) for(i = (a); i >= (b); --i)
#define CLR(a,b) memset(a,b,sizeof(a))
#define PB(x) push_back(x)

const int MAXN = 50010;
const int MAXM = 50010;
const int hash_size = 25000002;
const int INF = 0x7f7f7f7f;

bool vis[MAXN];
int cnt, n;
int maxb = -1, minb = INF;
int head[MAXN], dist[MAXN], cnt0[MAXN];
struct edge {
    int v, w, nxt;
}p[MAXM * 4];

void addedge(int u, int v, int w) {
    p[cnt].v = v;
    p[cnt].w = w;
    p[cnt].nxt = head[u];
    head[u] = cnt++;
}

int spfa(int x) {
    int i;

    CLR(cnt0, 0);
    CLR(vis, false);
    FORE(i, minb - 1, maxb)
        dist[i] = INF;
    dist[x] = 0;
    queue<int> q;
    q.push(x);
    vis[x] = true;
    ++cnt0[x];
    while(!q.empty()) {
        int u = q.front();
        q.pop();
        vis[u] = false;
        for(i = head[u]; i != -1; i = p[i].nxt) {
            int v = p[i].v;
            if(p[i].w + dist[u] < dist[v]) {
                dist[v] = p[i].w + dist[u];
                if(!vis[v]) {
                    q.push(v);
                    vis[v] = true;
                }
            }
        }
    }
    return dist[minb - 1];
}

void init() {
    int i, ai, bi, ci;

    while(scanf("%d", &n) != EOF) {
        cnt = 0;
        CLR(head, -1);
        maxb = -1, minb = INF;
        FORE(i, 1, n) {
            scanf("%d %d %d", &ai, &bi, &ci);
            addedge(bi, ai - 1, -ci);
            maxb = max(maxb, bi);
            minb = min(minb, ai);
        }
        FORE(i, minb, maxb) {
            addedge(i, i - 1, 0);
            addedge(i - 1, i, 1);
        }
        printf("%d\n", -spfa(maxb));
    }
}

int main() {
    init();
    return 0;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章