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.
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
差分约束问题,用贪心也挺简单,不断把区间右侧得数加入集合是的每个集合有俩个数出现在集合中,当然先排序按照右侧
端点排序;
#include<stdio.h>
#include<algorithm>
using namespace std;
struct node
{
int x;
int y;
}b[100001];
bool cmp(node a,node b)
{
return a.y<b.y;
}
int main()
{
int n,j,i,m[10001];
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d%d",&b[i].x,&b[i].y);
sort(b,b+n,cmp);
m[0]=b[0].y-1;
m[1]=b[0].y;
j=0;
for(i=1;i<n;i++)
{
if(b[i].x<=m[j]&&m[j+1]<=b[i].y)
{
continue;
}
if(m[j+1]>=b[i].x&&m[j]<b[i].x)
{
m[j+2]=b[i].y;
j=j+1;
}
if(m[j+1]<b[i].x)
{
m[j+2]=b[i].y-1;
m[j+3]=b[i].y;
j=j+2;
}
}
printf("%d\n",j+2);
}