拦截导弹

这题只是简单的动态规划+ 贪心算法

首先查找最多可以栏下几颗导弹。 用到了简单的动态规划, 可以通过二分查找的方式进行优化, 二分的时候要注意的是如果相同的数连在一起要一起放到队列里面去。

 

用贪心的时候, 我是用打表的方式, 从最小的开始, 看有没有哪个数符合的就修改如果没有的话, 就计数加一个

View Code
#include<stdio.h>
#include<string.h>
#define maxn 30003

int map[maxn], store[maxn];
int add[maxn];

int binary_find(int num, int x)
{
    int left = 1, right = num;
    int mid;

    while (left <= right)
    {
        mid = (left + right) >> 1;
        if (store[mid] >= x)
        {
            left = mid + 1;
        }
        else
        {
            right = mid - 1;
        }
    }
    return right + 1;
}

int main()
{
    int count, i, j, count_val;
    int n, mid, max;

    while (scanf("%d", &n) != EOF)
    {
        for (i = 1; i <= n; ++ i)
        {
            scanf("%d", &map[i]);
        }
        count  = 1;
        store[1] = map[1];

        for (i = 2; i <= n; ++ i)
        {
            mid = binary_find(count, map[i]);
            //printf("mid = %d\n", mid);
            if (mid > count)
            {
                ++ count;
            }
            store[mid] = map[i];
        }
        count_val = count;
        
        memset(add, 0, sizeof(add));
        max = map[1];
        add[max] = 1;
        count = 1;
        
        for (i = 2; i <= n; ++ i)
        {
            j = map[i]; 
            
            if (j <= max)
            {
               // printf("%d %d\n", max, add[max]);
                while (add[j] == 0) ++ j;
                add[j] = 0; 
                add[map[i]] = 1;   
                if (j == max) max = map[i]; //, printf("j = %d\n", j);  
            }
            else
            {
                ++ count;
                add[j] = 1;
                max = j;    
            }
        }
        
        printf("%d\n%d\n", count_val, count);
    }
    return 0;
}

 

posted @ 2012-07-21 23:57  CY_K_YC  阅读(246)  评论(0编辑  收藏  举报