[二分][dp] cf883I Photo Processing

本文介绍了一种将图片按对比度进行最优分组的算法。该算法利用了二分查找和动态规划技术来确保每组图片的数量不少于指定值的同时,最小化各组的最大处理时间。通过对输入数据排序并应用二分查找,结合动态规划检查每种可能的分组方案,最终找到最优化的分组方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@(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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值