标签:
题目链接:http://poj.org/problem?id=1276
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 29827 | Accepted: 10733 |
Description
Input
Output
Sample Input
735 3 4 125 6 5 3 350 633 4 500 30 6 100 1 5 0 1 735 0 0 3 10 100 10 50 10 10
Sample Output
735 630 0 0
Hint
Source
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <stack> 5 #include <queue> 6 #include <map> 7 #include <set> 8 #include <vector> 9 #include <cmath> 10 #include <algorithm> 11 using namespace std; 12 #define ll long long 13 const double eps = 1e-6; 14 const double pi = acos(-1.0); 15 const int INF = 0x3f3f3f3f; 16 const int MOD = 1000000007; 17 18 int dp[100005]; 19 int V,n,k[1005],w[1005]; 20 21 int main () 22 { 23 while (scanf ("%d",&V)==1) 24 { 25 scanf ("%d",&n); 26 for (int i=1; i<=n; i++) 27 scanf ("%d%d",&k[i],&w[i]); 28 memset(dp, 0, sizeof(dp)); 29 if (!V||!n){printf ("0\n");continue;} 30 int maxx=0;dp[0]=1; 31 for (int i=1; i<=n; i++) 32 { 33 for (int j=maxx; j>=0; j--) 34 { 35 if (dp[j]) 36 { 37 for (int l=1; l<=k[i]; l++) 38 { 39 if (j+l*w[i]>V) continue; 40 dp[j+l*w[i]]=1; 41 if (maxx<j+l*w[i]) maxx=j+l*w[i]; 42 } 43 } 44 } 45 } 46 printf ("%d\n",maxx); 47 } 48 return 0; 49 }
暴力水过,另附二进制优化代码,76msAC。
1 #include<cstdio> 2 #include<cstring> 3 #define Max(a, b) a>b?a:b 4 int dp[100005] ; 5 int val[105] ; 6 int main() 7 { 8 int cash, n, v, g, i, j, count ; 9 while(~scanf("%d%d", &cash, &n)) 10 { 11 if(!cash||!n) 12 { 13 while(n--) 14 scanf("%d%d", &g, &v) ; 15 printf("0\n") ; 16 continue ; 17 } 18 count = 0 ; 19 memset(dp, 0, sizeof(dp)) ; 20 while(n--) 21 { 22 scanf("%d%d", &g, &v) ; 23 //二进制优化 24 i = 1 ; 25 while(g>=i) 26 { 27 val[count++] = i * v ; 28 g -= i ; 29 i *= 2 ; 30 } 31 if(g) val[count++] = v * g ; 32 } 33 //01背包求解 34 for(i=0; i<count; i++) 35 { 36 for(j=cash; j>=val[i]; j--) 37 { 38 dp[j] = Max(dp[j], dp[j-val[i]]+val[i]) ; 39 } 40 } 41 printf("%d\n", dp[cash]) ; 42 } 43 return 0 ; 44 }
标签:
原文地址:http://www.cnblogs.com/dxd-success/p/4749074.html