gold_bridge

交流邮箱daijinqiao(at)163.com

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;
}




阅读更多
文章标签: intervals bi struct
个人分类: 图论 POJ ZOJ
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

zoj 1508 | poj 1201 Intervals

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭