该题就是01背包问题,一个常数优化,详细讲解见背包问题九讲
就是优化他的循环次数
不然会超时的
1 #include <stdio.h> 2 #include <string.h> 3 4 #define N 1000 5 6 int f[N*1003]; 7 int c[N]; 8 int w[N]; 9 10 int max(int n,int x) 11 { 12 return n > x?n:x; 13 } 14 15 int main() 16 { 17 int T; 18 scanf("%d",&T); 19 while(T--) 20 { 21 int n,m; 22 scanf("%d%d",&n,&m); 23 int i = 0; 24 memset(c,0,sizeof(c)); 25 memset(w,0,sizeof(w)); 26 27 for(i = 1; i <= n; i++) 28 scanf("%d%d",&c[i],&w[i]); 29 int j = 0; 30 memset(f,0,sizeof(f)); 31 32 int k = 0; 33 34 for(i = 1; i <= n; i++){ 35 int sum = 0; 36 for(k = i; k <= n; k++) 37 sum +=c[k]; 38 int d = max(m - sum,c[i]); 39 for(j = m; j >= d; j--) 40 if(f[j- c[i]] + w[i] > f[j]) 41 f[j] = f[j-c[i]] + w[i]; 42 } 43 printf("Max experience: %d\n",f[m]); 44 } 45 return 0; 46 }