二维费用背包。
1 #include <stdio.h> 2 #include <string.h> 3 4 #define mymax(a, b) (a>b) ? a:b 5 6 int dp[105][1005]; 7 int time[105], val[105]; 8 9 int main() { 10 int case_n; 11 int n, m, l; 12 int i, j, k; 13 14 scanf("%d", &case_n); 15 16 while (case_n--) { 17 scanf("%d%d%d", &n, &m, &l); 18 for (i=1; i<=n; ++i) 19 scanf("%d %d", &time[i], &val[i]); 20 memset(dp, 0xff, sizeof(dp)); 21 dp[0][0] = 0; 22 for (i=1; i<=n; ++i) { 23 for (k=m; k>0; --k) { 24 for (j=l; j>=time[i]; --j) { 25 if (dp[k-1][j-time[i]] != -1) { 26 dp[k][j] = mymax(dp[k][j], dp[k-1][j-time[i]]+val[i]); 27 } 28 } 29 } 30 } 31 k = 0; 32 for (i=0; i<=l; ++i) { 33 if (dp[m][i] > k) 34 k = dp[m][i]; 35 } 36 printf("%d ", k); 37 } 38 39 return 0; 40 }