http://acm.hdu.edu.cn/showproblem.php?pid=2639
The main idea is, to the backpack race bones, for the K-optimal solution, on the basis of the ordinary 01 backpack, add one-dimensional space, then f[i,v,k] can be understood as the first I items, put in the capacity v backpack, the value of the K-optimal solution. The time complexity is O (NVK).
Talk is cheap.
Look at the code.
ImportJava.util.Scanner; Public classBonecollector { Public Static voidMain (string[] sure) {intT; Scanner SC=NewScanner (system.in); T=Sc.nextint (); while(t--> 0) { intN, v, K; N=Sc.nextint (); V=Sc.nextint (); K=Sc.nextint (); int[] val =New int[n + 1]; int[] Vol =New int[n + 1]; int[] DP =New int[V + 2] [k + 2]; int[] tp_a =New int[k + 2]; int[] Tp_b =New int[k + 2]; for(inti = 0; I < n; i++) {Val[i]=Sc.nextint (); } for(inti = 0; I < n; i++) {Vol[i]=Sc.nextint (); } for(inti = 0; I < n; i++) { for(intj = V; J >= Vol[i]; j--) { for(intm = 1; M <= K; m++) {Tp_a[m]=Dp[j][m]; TP_B[M]= Dp[j-vol[i]][m] +Val[i]; } intTMP = 1, a = 1, b = 1; Tp_a[k+1] = tp_b[k+1] = 1; //loops, and sequentially saves the top K-optimal to the DP array while(TMP <= K && (a <= k | | b <=k)) {if(Tp_a[a] >Tp_b[b]) {Dp[j][tmp]=Tp_a[a]; A++; } Else{dp[j][tmp]=Tp_b[b]; b++; } if(dp[j][tmp]! = dp[j][tmp-1]) TMP++; }}} System.out.println (Dp[v][k]); } }}
01 Backpack for the first K---bone Collector II