[二分][dp] cf883I Photo Processing

@(ACM题目)[二分,dp]

Description

Evlampiy has found one more cool application to process photos. However the application has certain limitations.
Each photo i has a contrast vi. In order for the processing to be truly of high quality, the application must receive at least k photos with contrasts which differ as little as possible.
Evlampiy already knows the contrast vi for each of his n photos. Now he wants to split the photos into groups, so that each group contains at least k photos. As a result, each photo must belong to exactly one group.
He considers a processing time of the j-th group to be the difference between the maximum and minimum values of vi in the group. Because of multithreading the processing time of a division into groups is the maximum processing time among all groups.
Split n photos into groups in a such way that the processing time of the division is the minimum possible, i.e. that the the maximum processing time over all groups as least as possible.

Input

The first line contains two integers n and k ( 1kn3105 ) — number of photos and minimum size of a group.
The second line contains n integers v1, v2, …, vn ( 1vi109 ), where vi is the contrast of the i-th photo.

Output

Print the minimal processing time of the division into groups.

Sample Input

5 2
50 110 130 40 120

4 1
2 3 4 1

Sample Output

20

0

题目分析

数据sort预处理,二分查找答案是否<=mid。
对于mid,使用dp进行check。dp[i]:代表前i个位置中最后一个满足条件“答案<=mid”的位置。也就是说dp[i]存储一个位置j,满足j<=i, 且[1,j]这个子区间得到的答案不超过mid。dp[i] = max(j)。那么check的条件就是看dp[n]是否等于n。

代码

#include<bits/stdc++.h>
using namespace std;
const int maxn = 3e5 + 5;
int a[maxn], f[maxn]{0};//

int main()
{
    int n, k;
    scanf("%d%d", &n, &k);
    for(int i = 1; i <= n; ++i) scanf("%d", &a[i]);
    sort(a + 1, a + 1 + n);
    int l = -1, r = a[n] - a[1];
    while(l + 1 < r)
    {
        int mid = (l + r) >> 1;
        int pos = 0, t;
        for(int i = k; i <= n; ++i)
        {
            t = f[i - k];
            if(a[i] - a[t + 1] <= mid) pos = i;
            f[i] = pos;
        }
        if(f[n] == n) r = mid;
        else l = mid;
    }
    printf("%d\n", r);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/gdymind/article/details/78308273