http://acm.nyist.net/JudgeOnline/problem.php?pid=311
View Code
1 #include <stdio.h> 2 #define maxn 50005 3 #define INF -1 4 int ans[maxn],v[maxn],w[maxn]; 5 int main() 6 { 7 int t, n, m, i, j; 8 scanf("%d",&t); 9 while(t--) 10 { 11 scanf("%d%d",&n,&m); 12 for(i=0; i<n; i++) 13 scanf("%d%d",&v[i],&w[i]); 14 for(i=0; i<=m; i++) 15 ans[i]=INF; 16 ans[0]=0; 17 for(i=0; i<n; i++) 18 { 19 for(j=0; j<=m; j++) 20 if(j>=v[i] && ans[j-v[i]]!=-1 && ans[j-v[i]]+w[i]>ans[j]) 21 ans[j] = ans[j-v[i]]+w[i]; 22 } 23 if(ans[m] == INF) printf("NO\n"); 24 else printf("%d\n",ans[m]); 25 } 26 return 0; 27 }
看了下标程才恍然大悟,原来可以边输入边处理背包....自己一直都是先输入完...o(╯□╰)o