POJ 1201 Intervals(差分约束)
Intervals
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 30971 Accepted: 11990
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
题意:从ai到bi选ci个数,求最小的集合Z
分析:从题目可以读出是差分约束的题,然后推公式。
bi - ai + 1 >= ci
0 <= i + 1 - i <= 1
因为求最小值,所以求一次最长路就行
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
const int N = 1e6+10;
const int inf = 0x3f3f3f3f;
struct node{
int u, v, w, nxt;
}edge[N];
int n, cnt, mi, ma;
int fir[N], dis[N], num[N];
bool vis[N];
inline void built(int u, int v, int w){
edge[cnt] = (node){u, v, w, fir[u]};
fir[u] = cnt++;
}
inline int spfa(int st){
memset(vis, false, sizeof(vis));
vis[st] = true;
memset(num, 0, sizeof(num));
num[st]++;
for(int i = 0; i <= n; i++){
dis[i] = -inf;
}
dis[st] = 0;
queue<int> Q;
Q.push(st);
while(!Q.empty()){
int u = Q.front();
Q.pop();
vis[u] = false;
for(int i = fir[u]; i; i = edge[i].nxt){
int v = edge[i].v;
if(dis[v] < dis[u] + edge[i].w){
dis[v] = dis[u] + edge[i].w;
if(!vis[v]){
vis[v] = true;
Q.push(v);
num[v]++;
if(num[v] >= n)
return -1;
}
}
}
}
return dis[ma];
}
int main(){
#ifdef ONLINE_JUDGE
#else
freopen("in.txt", "r", stdin);
#endif // ONLINE_JUDGE
int a, b, c;
while(~scanf("%d", &n)){
cnt = 1;
mi = inf, ma = -inf;
memset(fir, 0, sizeof(fir));
for(int i = 1; i <= n; i++){
scanf("%d%d%d", &a, &b, &c);
built(a, b + 1, c);
mi = min(mi, a);
ma = max(ma, b);
}
ma++;
for(int i = mi; i < ma; i++){
built(i ,i + 1, 0);
built(i + 1, i, -1);
}
int ans = spfa(mi);
printf("%d\n", ans);
}
return 0;
}