nyoj 891 找点

找点

时间限制: 2000 ms  |  内存限制: 65535 KB
难度: 2
描述

上数学课时,老师给了LYH一些闭区间,让他取尽量少的点,使得每个闭区间内至少有一个点。但是这几天LYH太忙了,你们帮帮他吗?

输入
多组测试数据。
每组数据先输入一个N,表示有N个闭区间(N≤100)。
接下来N行,每行输入两个数a,b(0≤a≤b≤100),表示区间的两个端点。
输出
输出一个整数,表示最少需要找几个点。
样例输入
4
1 5
2 4
1 4
2 3
3
1 2
3 4
5 6
1
2 2
样例输出
1
3

1


此题是对前辈所写代码的总结,已AC仅供参考

法一:

#include<stdio.h>
#include<stdlib.h>
struct in
{
	int x;
	int y;
}c[105];
int cmp(const void *a,const void *b)
{
   /*struct in *c=(struct in *)a;
   struct in *d=(struct in *)b;
   return c->x-d->x;*/<br style="font-family: Arial; font-size: 14px; line-height: 26px;" /><span style="font-family: Arial; font-size: 14px; line-height: 26px;">  </span>  return *(int *)a-*(int *)b;//只将X从小到大排序 
}
int main()
{
	int n;
	while(scanf("%d",&n)!=EOF)
	{
		int t,i,k=1;
		for(i=0;i<n;i++)
		   scanf("%d%d",&c[i].x,&c[i].y);
		qsort(c,n,sizeof(c[0]),cmp);//排序 
		t=c[0].y;
		for(i=1;i<n;i++)
		{
			if(t>c[i].x && t>c[i].y)
			     t=c[i].y;
			else if(t<c[i].x)
				{
					k++;
					t=c[i].y;
				}
		}
		printf("%d\n",k);
	}
	return 0;
}



 
     
    

贪心算法之一:区间选点问题

因为从小的区间中选取一点,在包含这个小区间的大区间不必考虑所以

把所有的区间按b由小到大排序,当b相等时,按a由大到小排序,使得小区间在上,大区间在下

如:

1.   1 . . . .5

2.      2 . . . 6

3.    1 . . . . 6

4.         4 . . .7

5.                     9 . . . .14

6.                             12 . .15

根据贪心策略,选取最后一个点,当下一段区间的a>最后一个时,更改最后一个点为下一段区间最后一个点,同时点数++

如第4, 5段的情况

用贪心方法理解这个例子,先选5,直到第5段,则更改点位14,点数++,继续判断

#include<algorithm>
#include<cstring>
#include<cstdlib>
using namespace std;
struct node
{
	int x, y;
};
node l[105];
bool comp(const node& a, const node &b)
{
	if (a.y != b.y)
	{
		return a.y<b.y;
	}
	else
	    return a.x>b.x;    //这一点的理解参见qsort();百度百科
}
int main(){
	int N;
	while (cin >> N){
		memset(l, 0, sizeof(l));
		for (int i = 0; i<N; i++)
		{
			int a, b;
			cin >> a >> b;
			l[i].x = a, l[i].y = b;
		}
		sort(l, l + N, comp);
		/*for(int i=0;i<N;i++){
			cout<<l[i].x<<" "<<l[i].y<<endl;
		}*/
		int cont=l[0].y,sum=1;
		for(int i=1;i<N;i++)
		{
			if(l[i].x>cont)
			{
				cont=l[i].y;
				sum++;
			}
		} 
		cout<<sum<<endl;
	}
}


 
   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值