题解:P13416 [COCI 2012/2013 #4] RAZLIKA

· · 题解

分享一种不一样的做法(不同于另外两篇题解)。

我们不使用双端队列,而是用更常用的方法:优先队列!

为了方便表述,以下的 a 数组均指代题目中的 V 数组。

我们很容易发现,对于排序完的 a 数组,删除的数字一定是一个连续的子序列。

所以我们对于排好序的 a 数组,记录两个数之间的差值,然后对于 1\sim n 的范围,看看哪段长度为 n-k 的区间中差值的最小值与这段区间末位置和初位置的差值之和最小,最后统计答案。

其中记录区间最小值是提高组和普及组都常用的一种操作,我们可以使用优先队列实现。每次将当前值入小根堆,求最小值的时候先将小根堆上头之前的值去掉,这样子就避免了 O(n^2) 的复杂度,降到了 O(2n)。

代码如下:

#include <bits/stdc++.h>
using namespace std;
const int N = 1100000;
int n, k, a[N], sum[N], ans = 1e9;
priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > q;
signed main () {
    scanf("%d%d", &n, &k);
    for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
    sort(a + 1, a + n + 1);
    for (int i = 2; i <= n; i++) sum[i] = a[i] - a[i - 1];
    for (int i = 2; i <= n; i++) {
        int lst = i - (n - k) + 1;
        q.push(make_pair(sum[i], i));
        if (lst >= 1) {
            while (q.top().second < lst) q.pop();
            ans = min(ans, a[i] - a[lst] + q.top().first);
        }
    }
    printf("%d", ans);
    return 0;
}