Time limit : 2sec / Memory limit : 1024MB
Score : 400 points
Problem Statement
There are N islands lining up from west to east, connected by N−1 bridges.
The i-th bridge connects the i-th island from the west and the (i+1)-th island from the west.
One day, disputes took place between some islands, and there were M requests from the inhabitants of the islands:
Request i: A dispute took place between the ai-th island from the west and the bi-th island from the west. Please make traveling between these islands with bridges impossible.
You decided to remove some bridges to meet all these M requests.
Find the minimum number of bridges that must be removed.
Constraints
- All values in input are integers.
- 2≤N≤105
- 1≤M≤105
- 1≤ai<bi≤N
- All pairs (ai,bi) are distinct.
Input
Input is given from Standard Input in the following format:
N M
a1 b1
a2 b2
:
aM bM
Output
Print the minimum number of bridges that must be removed.
Sample Input 1
Copy
5 2
1 4
2 5
Sample Output 1
Copy
1
The requests can be met by removing the bridge connecting the second and third islands from the west.
Sample Input 2
Copy
9 5
1 8
2 7
3 5
4 6
7 9
Sample Output 2
Copy
2
Sample Input 3
Copy
5 10
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5
Sample Output 3
Copy
4
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long ll;
struct node{
int l,r;
}a[100000+20];
bool cmp(node a,node b)
{
if(a.r==b.r)
return a.l<b.l;//右边相同比较左边
return a.r<b.r;//对数据右排序
}
int main ()
{
int n,m,i;
scanf("%d%d",&n,&m);
for(i=0;i<m;i++)
scanf("%d %d",&a[i].l,&a[i].r);
int mn=a[0].r;
for(i=0;i<m;i++)
mn=min(a[i].r,mn);
sort(a,a+m,cmp);//排序
int now=mn,ans=1;//找到最小的
for(i=1;i<m;i++)
{
if(a[i].l>=now)
{
now=a[i].r;//如果下一个数据的左边大于切断桥的右边则仍然需要切桥
ans++;
}
}
printf("%d\n",ans);
return 0;
}
切的桥始终在右区间的。