[CF985E] Pencils and Boxes

[CF985E] Pencils and Boxes - dp,双指针

Description

对 n 个整数分组,每个数恰好分入一组中,每组必须包含至少 k 个数,每组中的数值极差不能超过 d,判断是否存在满足条件的分组方案。

Solution

最容易想到的那种贪心是有问题的,需要稍微改一下

(f[i]) 表示做到第 i 个数是否合法,那么朴素的 (O(n^2)) dp 是显然的

但显然 dp 的转移来源是单调的,因此可以借用决策单调性的想法,具体实现类似双指针

#include <bits/stdc++.h>
using namespace std;

#define int long long
const int N = 1000005;

int a[N], f[N], n, k, d;

signed main()
{
    ios::sync_with_stdio(false);

    cin >> n >> k >> d;
    for (int i = 1; i <= n; i++)
        cin >> a[i];
    sort(a + 1, a + n + 1);
    a[n + 1] = 1e18;
    int j = 1;
    f[0] = 1;
    for (int i = 0; i <= n; i++)
        if (f[i])
        {
            j = max(j, i + k);
            if (j > n)
                break;
            while (a[j] - a[i + 1] <= d)
                f[j++] = 1;
        }
    cout << (f[n] ? "YES" : "NO") << endl;
}
原文地址:https://www.cnblogs.com/mollnn/p/14378785.html