Integer Intervals
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 14560 | Accepted: 6174 |
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
给出n个区间,求一个点集,使得每个区间至少有两点在点集内,注意点集可以不连续
将区间按右端点升序排列,选两个点,比较是否满足区间然后更新即可
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<string>
#include<cstring>
#include<vector>
#include<map>
#include<queue>
#include<iostream>
#define PI acos(-1.0)
#define inf 0x3f3f3f3f
using namespace std;
const int maxn = 1e5+10;
typedef long long LL;
using namespace std;
struct node{
int x, y;
} sec[maxn];
bool cmp(const node &a, const node &b){
if(a.y == b.y) return a.x < b.x;
return a.y < b.y;
}
int main(){
int n, x, y;
cin >> n;
for(int i = 0; i < n; i++) scanf("%d%d", &sec[i].x, &sec[i].y);
sort(sec, sec+n, cmp);
int l = sec[0].y-1;
int r = sec[0].y;
int ans = 2;//区间升序排列,取两个靠右的点
for(int i = 1; i < n; i++){
if(l >= sec[i].x) continue;//左点>=区间左端点,不需要更新点,这对点同时满足这两个区间
else if(r >= sec[i].x && l < sec[i].x){//右点>=区间左端点,左点小于,将左点更新为此区间左端点,右点更新为区间右端点(点集不连续,尽量向右取)
ans++;
l = r;
r = sec[i].y;
}
else{//都不满足,两点更新为区间右侧两点
ans += 2;
r = sec[i].y;
l = r-1;
}
}
cout << ans << endl;
return 0;
}