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
题目大意:给定n个区间,再给出一个集合,集合中包含一些数,使得每个区间中至少有两个点在该集合中,求该集合最少包含几个数。
题目分析:
这算是区间选点问题的升级版,解法也与区间选点问题类似。
1.首先还是将区间按照右端点进行排序。
2.这个题要维护两个点(t和u,保证t>u)。因此会有两种情况:
1)a[i].l>t,说明区间与集合没有任何交点,因此要将t和u都更新t=a[i].r,u=t-1
2)a[i].l<=t&&a[i].l>u,说明区间和集合只有一个交点所以只需要更新一个点的坐标但因为要保证t>u,所以u=t,t=a[i].r
代码如下:
#include <iostream>
#include <cstdio>
#include <cmath>
#include <set>
#include <queue>
#include <vector>
#include <string>
#include <cstring>
#include <sstream>
#include <algorithm>
#define LL long long
#define PII pair<int,int>
using namespace std;
const int N=1e4+5;
struct Node{
int l,r;
bool operator<(const Node &a) const//定义排序准则
{
return r<a.r;//按右端点进行排序
}
}a[N];
int main()
{
int n;
cin>>n;
for(int i=0;i<n;i++)
cin>>a[i].l>>a[i].r;
sort(a,a+n);
int ans=2,t=a[0].r,u=t-1; //初始化两个点
for(int i=1;i<n;i++)
{
if(a[i].l>t) //第一种情况
{
ans+=2;
t=a[i].r;
u=t-1;
}
else if(a[i].l>u) //第二种情况
{
ans++;
u=t;
t=a[i].r;
}
}
cout<<ans<<endl; //输出结果
return 0;
}