@(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 (1 ≤ k ≤ n ≤ 3⋅105) — number of photos and minimum size of a group.
The second line contains n integers v1, v2, …, vn (1 ≤ vi ≤ 109), 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 1204 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;
}

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

被折叠的 条评论
为什么被折叠?



