upc Islands War#贪心

问题 K: Islands War
时间限制: 1 Sec 内存限制: 128 MB

题目描述
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 is given from Standard Input in the following format:

N M
a1 b1
a2 b2
:
aM bM

输出
Print the minimum number of bridges that must be removed.
样例输入 Copy
5 2
1 4
2 5
样例输出 Copy
1
提示
The requests can be met by removing the bridge connecting the second and third islands from the west.

 /**
贪心
1 4
2 5
把数据经过排序之后形成东西走向有序的岛屿
如果第二组数据的左端点大于等于上一个数据的右端点
说明两个区间不存在相交的区间
也就是说明两个区间都要切断一座桥
即ans++ 
**/
struct node
{
	int l;
	int r;
}a[maxn];

bool cmp(node x,node y)
{
	if(x.r == y.r)	return x.l < y.l;//右端点相同的话按照左端点升序排列
	return x.r < y.r;//否则就按照右端点升序排列 
}

int n,m,ans;
int main()
{
	n = read();	m = read();
	for(int i=0;i<m;i++)
		cin >> a[i].l >> a[i].r;
	sort(a,a+m,cmp);
	int t = a[0].r;	
	ans = 1;
	for(int i=1;i<m;i++)
	{
		if(a[i].l >= t) 
		{
			ans++;
			t = a[i].r;
			//如果这一个左端点大于上一个右端点,切断桥数+1,更新t 
		}
	}
	cout << ans << endl;
	return 0;
}
发布了42 篇原创文章 · 获赞 0 · 访问量 655

猜你喜欢

转载自blog.csdn.net/magic_wenge/article/details/105072686
UPC