POJ1201 Intervals(差分约束)

题意:给出n个闭区间[ai, bi],每个区间还有个正整数ci,表示需要在区间i中至少取到ci个数。求要满足所有的n个约束条件,最少要取多少个数字。

 

思路:设S(k)为从区间[0,k]中取到的数字的个数,则 S(bi) - S(ai - 1) >= ci

另外有 0 <= S(i) - S(i - 1) <= 1,(i = 0,1,...,n-1)

为了方便计算,将所有下标向右移1位,设mx = max(bi),则结果应为 min(S(mx) - S(0)),S(0) = 0。

要求最小值,用spfa求最长路即可。

 

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <stack>
#include <cmath>
#include <list>
#include <cstdlib>
#include <set>
#include <string>

using namespace std;

typedef long long ll;
const int inf = 0x3f3f3f3f;
const int maxn = 50005;
struct edg{
    int v, nxt, w;
}G[maxn << 2];
int tot, pre[maxn];
int n, dis[maxn], mx;
bool vis[maxn];
void add(int u, int v, int w) {
    G[tot].v = v;
    G[tot].w = w;
    G[tot].nxt = pre[u];
    pre[u] = tot++;
}
int spfa(){
    for (int i = 1; i <= mx; ++i) {
        dis[i] = -inf;
    }
    memset(vis, 0, sizeof(vis));
    queue<int> que;
    que.push(0);
    dis[0] = 0;
    vis[0] = true;
    while (!que.empty()) {
        int u = que.front();
        que.pop();
        vis[u] = false;
        for (int i = pre[u]; ~i; i = G[i].nxt) {
            int v = G[i].v, w = G[i].w;
            if (dis[u] + w > dis[v]) {
                dis[v] = dis[u] + w;
                if (!vis[v]) {
                    vis[v] = true;
                    que.push(v);
                }
            }
        }
    }
    return dis[mx];
}
int main(){
    int a, b, c;
    scanf("%d", &n);
    tot = 0;
    mx = 0;
    memset(pre, -1, sizeof(pre));
    for (int i = 0; i < n; ++i) {
        scanf("%d%d%d", &a, &b, &c);
        if (b >= mx) {
            mx = b + 1;
        }
        add(a, b + 1, c);
        //printf("%d %d %d\n", a, b + 1, c);
    }
    for (int i = 1; i <= mx; ++i) {
        add(i - 1, i, 0);
        add(i, i - 1, -1);
        //printf("%d %d %d\n", i - 1, i, 0);
        //printf("%d %d %d\n", i, i - 1, -1);
    }
    printf("%d\n", spfa());
    return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值