Integer Intervals
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 13676 Accepted: 5827
传送门
Description
An integer interval [a,b], a < b, is a set of all consecutive integers beginning with a and ending with b.
Write a program that: finds the minimal number of elements in a set containing at least two different integers from each interval.
Input
The first line of the input contains the number of intervals n, 1 <= n <= 10000. Each of the following n lines contains two integers a, b separated by a single space, 0 <= a < b <= 10000. They are the beginning and the end of an interval.
Output
Output the minimal number of elements in a set containing at least two different integers from each interval.
Sample Input
4
3 6
2 4
0 2
4 7
Sample Output
4
Source
CEOI 1997
/*
差分约束.
维护三个不等式.
先找出上下界x,y.
那么答案贡献必定在 [x,y]里.
dis[i]表示1到i的贡献.
*/
#include<iostream>
#include<cstdio>
#define MAXN 20001
using namespace std;
int dis[MAXN],n,m,x=0x7777ffff,y;
bool flag;
struct data
{
int l;
int r;
}
s[MAXN];
int main()
{
int x1,y1;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d %d",&x1,&y1);
s[i].l=x1;
s[i].r=y1+1;
x=min(s[i].l,x);
y=max(s[i].r,y);
}
while(!flag)
{
flag=true;
for(int i=1;i<=n;i++)
if(dis[s[i].l]>dis[s[i].r]-2)
dis[s[i].l]=dis[s[i].r]-2,flag=false;
for(int i=x;i<y;i++)
if(dis[i+1]>dis[i]+1)
dis[i+1]=dis[i]+1,flag=false;
for(int i=x;i<y;i++)
if(dis[i]>dis[i+1])
dis[i]=dis[i+1],flag=false;
}
printf("%d",dis[y]-dis[x]);
return 0;
}