POJ 3069 Saruman's Army

简单贪心。问题等价于给你n个区间,选择最少数量的区间,使这些选出来的区间覆盖住[1,n]。

#include<cstdio>
#include<cstring>
#include<cmath>
#include<stack>
#include<algorithm>
using namespace std;

const int maxn = 1000 + 10;
int xmax, R, n;
int x[maxn];
struct Seg
{
    int l, r;
}seg[maxn];
bool flag[maxn];

int main()
{
    while (~scanf("%d%d", &R, &n))
    {
        if (R == -1 && n == -1) break;
        for (int i = 1; i <= n; i++) scanf("%d", &x[i]);
        sort(x + 1, x + 1 + n);
        for (int i = 1; i <= n; i++)
        {
            for (int j = i; j >= 1; j--) if (x[i] - x[j] <= R) seg[i].l = j;
            for (int j = i; j <= n; j++) if (x[j] - x[i] <= R) seg[i].r = j;
        }

        int e = 0; memset(flag, 0, sizeof flag);
        int ans = 0;
        while (1)
        {
            int pos = -1;
            int maxlen = -1;
            for (int i = 1; i <= n; i++)
            {
                if (!flag[i])
                {
                    if (seg[i].l <= e + 1 && seg[i].r > maxlen)
                    {
                        maxlen = seg[i].r;
                        pos = i;
                    }
                }
            }
            flag[pos] = 1;
            e = seg[pos].r;
            ans++;
            if (e >= n) break;
        }
        printf("%d\n", ans);
    }
    return 0;
}

 

posted @ 2016-03-10 20:24  Fighting_Heart  阅读(130)  评论(0编辑  收藏  举报