//最小拦截系统,解题思路:一个数组a[n]保存将要过来的导弹;数组h[10001]保存每一个系统的最高拦截高度;随着导弹来临,h[10001]不断更新;时间复杂度为O[n的平方];最后输出的是h[10001]的最大下标,用count来计数.思路很清晰,代码很短.
#include <stdio.h>
#include <iostream>
using namespace std;
int n = 0;
int main(int argc, char *argv[])
{
while(cin>>n)//导弹数目
{
int count = 0;
int a[n];//保存每一个导弹的高度
int h[10001];//保存系统的最高拦截高度
for(int i = 0; i < n; i++)
scanf("%d",&a[i]);
h[count] = a[0];//第一个系统的最高高度为第一个导弹的高度
for(int i = 0; i < n; i++)
{
for(int j = 0; j <= count; j++)
{
if(h[j] >= a[i])//如果第 i 个导弹的高度小于第 j 个系统的拦截高度
{
h[j] = a[i];
break;
}
}
if(h[count] < a[i])
h[++count] = a[i];//如果第 i 个导弹的高度大于所有的拦截系统时,就添加一个新系统吧
}
printf("%d\n",count+1);
}
return 0;
}
//其实还可以进一步优化,在为第i个导弹寻找拦截系统时,可以用二分搜索法找到合适的系统由此时间复杂度优化为O(nlogn).HDOJ1257
最新推荐文章于 2021-05-23 20:49:31 发布
517

被折叠的 条评论
为什么被折叠?



