Intervals
Time Limit: 2000MS | | Memory Limit: 65536K |
Total Submissions: 31592 | | Accepted: 12214 |
Description
You are given n closed, integer intervals [ai, bi] and n integers c1, ..., cn.
Write a program that:
reads the number of intervals, their end points and integers c1, ..., cn from the standard input,
computes the minimal size of a set Z of integers which has at least ci common elements with interval [ai, bi], for each i=1,2,...,n,
writes the answer to the standard output.
Input
The first line of the input contains an integer n (1 <= n <= 50000) -- the number of intervals. The following n lines describe the intervals. The (i+1)-th line of the input contains three integers ai, bi and ci separated by single spaces and such that 0 <= ai <= bi <= 50000 and 1 <= ci <= bi - ai+1.
Output
The output contains exactly one integer equal to the minimal size of set Z sharing at least ci elements with interval [ai, bi], for each i=1,2,...,n.
Sample Input
5
3 7 3
8 10 3
6 8 1
1 3 1
10 11 1
Sample Output
6
Source
Southwestern Europe 2002
题意:
给出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)
(原因0~i之间选出的数看到比0~i-1之间多,每一个数只能被选一次)
为了方便计算,将所有下标向右移1位,设mx = max(bi),则结果应为 min(S(mx) - S(0)),S(0) = 0。
要求最小值,用spfa求最长路即可。
#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 500006, M = 5000006;
int n, m, d[N];
int Head[N], ver[M], Leng[M], Next[M], tot;
bool v[N];
inline void add(int x, int y, int z) {
ver[++tot] = y;
Leng[tot] = z;
Next[tot] = Head[x];
Head[x] = tot;
}
void spfa() {
queue<int> q;
q.push(0);
v[0] = 1;
d[0] = 0;
while (q.size()) {
int x = q.front();
q.pop();
v[x] = 0;
for (int i = Head[x]; i; i = Next[i]) {
int y = ver[i];
if (d[y] < d[x] + Leng[i]) { ///最长路
d[y] = d[x] + Leng[i];
if (!v[y]) {
v[y] = 1;
q.push(y);
}
}
}
}
}
int main() {
while(scanf("%d",&n)!=-1)
{
memset(v,0,sizeof(v));
memset(d, 0xcf, sizeof(d));
memset(Head, 0, sizeof(Head));
tot = m = 0;
for (int i = 1; i <= n; i++) {
int x, y, z;
scanf("%d %d %d", &x, &y, &z);
add(x, y + 1, z) ;
m = max(m, y + 1);
}
for (int i = 1; i <= m; i++) {
add(i - 1, i, 0);
add(i, i - 1, -1);
}
spfa();
printf("%d\n",d[m]);
}
return 0;
}