此题是二维的背包问题,不会的请先看《背包九讲》(虽然我也没看明白,但还是值得一看),这里再说一句,学算法最好是拿例题来实践,而实践最好是要有大量测试数据,
能过测试数据能够很明确地找出自己的错误来,并且能使人对算法的处理过程有个很明朗的了解。希望各大OJ网站能够高抬贵手,像USCAOG 一样将后台测试数据展现出来,帮助更多在错误中死去活来的 acmer 们走出迷途!
/* THE PROGRAM IS MADE BY PYY */ /*----------------------------------------------------------------------------// Copyright (c) 2011 panyanyany All rights reserved. URL : http://acm.hdu.edu.cn/showproblem.php?pid=2159 Name : 2159 FATE Date : Saturday, August, 06, 2011 Time Stage :6 hours around Result: 4348182 2011-08-06 16:27:14 Accepted 2159 15MS 228K 1399 B C++ pyy Test Data: Review: //----------------------------------------------------------------------------*/ #include <stdio.h> #include <string.h> #define max(a, b) (((a) > (b)) ? (a) : (b)) #define min(a, b) (((a) < (b)) ? (a) : (b)) #define MAXSIZE 101 int need, remain, kind, kill ; int val[MAXSIZE], cost[MAXSIZE], dp[MAXSIZE][MAXSIZE] ; int twoDimension () { int i, j, k ; memset (dp, 0, sizeof (dp)) ; for (i = 1 ; i <= kind ; ++i) { for (j = 1 ; j <= kill ; ++j) { for (k = cost[i] ; k <= remain ; ++k) { dp[j][k] = max (dp[j][k], dp[j-1][k-cost[i]] + val[i]) ; } } } // 一开始在外面加了层1.....kill 的循环,想找到杀怪数最少并且忍耐度消耗最少 // 时最先到达need 的值,结果一直错。 // 因为有可能杀一只怪,消耗的忍耐度比杀五只怪还大 for (i = 1 ; i <= remain ; ++i) { // printf ("%d,%d ", dp[kill][i], i) ; if (dp[kill][i] >= need) break ; } // puts ("") ; if (i > remain) return -1 ; return remain - i ; } int main () { int i, j ; while (scanf ("%d%d%d%d", &need, &remain, &kind, &kill) != EOF) { for (i = 1 ; i <= kind ; ++i) { scanf ("%d%d", &val[i], &cost[i]) ; } printf ("%d\n", twoDimension ()) ; } return 0 ; }