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