题意:
数轴上有 n 个闭区间 [a_i, b_i]。取尽量少的点,使得每个区间内都至少有一个点(不同区间内含的点可以是同一个)。
input:
第一行1个整数N(N<=100)
第2~N+1行,每行两个整数a,b(a,b<=100)
output:
一个整数,代表选点的数目
examples:
Input
2
1 5
4 6
Output
1
Input
3
1 3
2 5
4 6
Output
2
思路:
定义一个结构体,其中包括左端点和右端点。输入区间数及各区间,对区间进行排序。当一个区间的左端点在第一个区间 右端点的右边时,点数增加。之后以后面区间的右端点去和之后的区间左端点进行比较。而如果遍历的区间的左端点小于进行比较的区间左端点,则表明它们拥有相同的点,则点数不需增加。
代码:
#include<iostream>
#include<algorithm>
using namespace std;
struct node{
int left;
int right;
operator<(const node &te) const
{
if(right!=te.right)
return right<te.right;
return left>te.left;
}
};
int main()
{
int n;
cin>>n;
//int left[n]={0};
//int right[n]={0};
//int count=1;
node temp[n]={0};
//int count=0;
int count=1;
//while(cin>>n)
//for(int i=0;i<n;i++)
//{
for(int i=0;i<n;i++)
{
//cin>>left[i]>>right[i];
cin>>temp[i].left>>temp[i].right;
}
sort(temp,temp+n);
int m=temp[0].right;
//count++;
for(int j=1;j<n;j++)
{
//if(right[j]<left[j+1])
//if(temp[j].right<temp[j+1].left)
if(m<temp[j].left)
{
count++;
//right[j]=right[j+1];
//temp[j].right=temp[j+1].right;
m=temp[j].right;
}
}
cout<<count<<endl;
return 0;
}