区间相交问题


区间相交问题
Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u

Description

给定 x 轴上 n 个闭区间。去掉尽可能少的闭区间,使剩下的闭区间都不相交。

★算法设计: 对于给定的 n 个闭区间,计算去掉的最少闭区间数。

Input

对于每组输入数据,输入数据的第一行是正整数 n (1<=n<=40,000),表示
闭区间数。接下来的 n 行中,每行有 2 个整数,分别表示闭区间的 2 个端点。

Output

输出计算出的去掉的最少闭区间数。

Sample Input

3
10 20
15 10
20 15

Sample Output

2

代码:

#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;

struct T
{
	int head;   //区间首部 
	int tail;   //区间尾部 
}a[40010];

bool cmp(struct T a, struct T b) {//贪心策略:尾部按照从小到大排列,并且第一个区间一定要选 
	return a.tail < b.tail;
}

int main()
{
	int m;
	while(~scanf("%d", &m)) {//多组数据输入 
		for(int i = 0; i < m; i++) {
			scanf("%d %d", &a[i].head, &a[i].tail);
			int t;
			if(a[i].head > a[i].tail) //交换首尾部,使首部小于尾部 
			{
				t = a[i].head;
				a[i].head = a[i].tail;
				a[i].tail = t;
			}
		}
		sort(a, a+m, cmp);   //排序 
		int n = a[0].tail;
		int sum = 0;
		for(int i = 1; i < m; i++) {
			if(a[i].head <= n)
			sum++;
			else n = a[i].tail;
		}
		printf("%d\n", sum);
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值