hdu2639 Bone Collector II--01背包K优解
发布日期:2021-10-03 20:32:27 浏览次数:1 分类:技术文章

本文共 2671 字,大约阅读时间需要 8 分钟。

原题链接:

一:原题内容

Problem Description
The title of this problem is familiar,isn't it?yeah,if you had took part in the "Rookie Cup" competition,you must have seem this title.If you haven't seen it before,it doesn't matter,I will give you a link:
Here is the link:
Today we are not desiring the maximum value of bones,but the K-th maximum value of the bones.NOTICE that,we considerate two ways that get the same value of bones are the same.That means,it will be a strictly decreasing sequence from the 1st maximum , 2nd maximum .. to the K-th maximum.
If the total number of different values is less than K,just ouput 0.
Input
The first line contain a integer T , the number of cases.
Followed by T cases , each case three lines , the first line contain two integer N , V, K(N <= 100 , V <= 1000 , K <= 30)representing the number of bones and the volume of his bag and the K we need. And the second line contain N integers representing the value of each bone. The third line contain N integers representing the volume of each bone.
 
Output
One integer per line representing the K-th maximum of the total value (this number will be less than 2
31).
Sample Input
35 10 21 2 3 4 55 4 3 2 15 10 121 2 3 4 55 4 3 2 15 10 161 2 3 4 55 4 3 2 1
Sample Output
1220
 
二:分析理解
第K优解问题
其基本思想是将每个状态都表示成有序队列,将状态转移方程中的max/min转化成有序队列的合并。这里仍然以01背包为例讲解一下。
首 先看01背包求最优解的状态转移方程:f[i][v]=max{f[i-1][v],f[i-1][v-c[i]]+w[i]}。如果要求第K优解,那么 状态f[i][v]就应该是一个大小为K的数组f[i][v][1..K]。其中f[i][v][k]表示前i个物品、背包大小为v时,第k优解的值。 “f[i][v]是一个大小为K的数组”这一句,熟悉C语言的同学可能比较好理解,或者也可以简单地理解为在原来的方程中加了一维。显然f[i][v] [1..K]这K个数是由大到小排列的,所以我们把它认为是一个有序队列。
然 后原方程就可以解释为:f[i][v]这个有序队列是由f[i-1][v]和f[i-1][v-c[i]]+w[i]这两个有序队列合并得到的。有序队列 f[i-1][v]即f[i-1][v][1..K],f[i-1][v-c[i]]+w[i]则理解为在f[i-1][v-c[i]][1..K]的每 个数上加上w[i]后得到的有序队列。合并这两个有序队列并将结果的前K项储存到f[i][v][1..K]中的复杂度是O(K)。最后的答案是f[N] [V][K]。总的复杂度是O(VNK)。
01背包再清楚不过了,主要还是是有序队列合并的问题。
三:AC代码
#include
#include
using namespace std;int T;int N, V, K;int A[35], B[35];int va[105], vo[105];int dp[1005][35];int main(){ scanf("%d", &T); while (T--) { scanf("%d%d%d", &N, &V, &K); memset(dp, 0, sizeof(dp)); for (int i = 1; i <= N; i++) scanf("%d", &va[i]); for (int i = 1; i <= N; i++) scanf("%d", &vo[i]); for (int i = 1; i <= N; i++) { for (int j = V; j >= vo[i]; j--) { for (int k = 1; k <= K; k++) { A[k] = dp[j - vo[i]][k] + va[i]; B[k] = dp[j][k]; } A[K + 1] = -1; B[K + 1] = -1; int a, b, c; a = b = c = 1; while (c <= K && (A[a] != -1 || B[b] != -1)) { if (A[a] > B[b]) dp[j][c] = A[a++]; else dp[j][c] = B[b++]; if (dp[j][c] != dp[j][c - 1])//去重 c++; } } } printf("%d\n", dp[V][K]); } return 0;}

转载地址:https://blog.csdn.net/LaoJiu_/article/details/51201569 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:hdu1171 Big Event in HDU --01背包
下一篇:hdu2602 Bone Collector--01背包

发表评论

最新留言

不错!
[***.144.177.141]2024年04月06日 01时56分51秒