HDU 1257 最少拦截系统 (贪心)

106 阅读1分钟

题意:

中文题目很明显,就是用已有系统去拦截导弹,如果当前系统所能拦截的高度低于导弹的高度,那就要再开一个系统。可以用贪心的思想,当知道导弹的高度之后就用高度最接近它的系统去拦截。我用了lower_bound()这个函数寻找最合适的系统,这个函数是二分查找,避免超时,毕竟数据有30000。

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int lan[30010];
int main(){	
	int n,h,k;
	while(scanf("%d",&n)!=EOF){
		int co=0;
		memset(lan,0,sizeof(lan));
		for(int i=0;i<n;i++){
			scanf("%d",&h);
			k = lower_bound(lan,lan+co,h)-lan;//这个函数使用二分查找,在lan中找到大于等于h的数的地址 
			if(k==co) lan[co++]=h-1;
			else (lan[k]=h-1);
		}
		printf("%d\n",co);
	}
	return 0;
}
//		upper_bound()同样是二分查找,返回等于h的数的地址

\