题目链接: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
#include <iostream> #include <cstdio> #include <cstring> #include <stack> #include <queue> #include <map> #include <set> #include <vector> #include <cmath> #include <algorithm> using namespace std; #define ll long long const double eps = 1e-6; const double pi = acos(-1.0); const int INF = 0x3f3f3f3f; const int MOD = 1000000007; int dp[100005]; int V,n,k[1005],w[1005]; int main () { while (scanf ("%d",&V)==1) { scanf ("%d",&n); for (int i=1; i<=n; i++) scanf ("%d%d",&k[i],&w[i]); memset(dp, 0, sizeof(dp)); if (!V||!n){printf ("0\n");continue;} int maxx=0;dp[0]=1; for (int i=1; i<=n; i++) { for (int j=maxx; j>=0; j--) { if (dp[j]) { for (int l=1; l<=k[i]; l++) { if (j+l*w[i]>V) continue; dp[j+l*w[i]]=1; if (maxx<j+l*w[i]) maxx=j+l*w[i]; } } } } printf ("%d\n",maxx); } return 0; }
760ms暴力过的,另附上某大神二进制优化代码,76msAC。
#include<cstdio>
#include<cstring>
#define Max(a, b) a>b?a:b
int dp[100005] ;
int val[105] ;
int main()
{
int cash, n, v, g, i, j, count ;
while(~scanf("%d%d", &cash, &n))
{
if(!cash||!n)
{
while(n--)
scanf("%d%d", &g, &v) ;
printf("0\n") ;
continue ;
}
count = 0 ;
memset(dp, 0, sizeof(dp)) ;
while(n--)
{
scanf("%d%d", &g, &v) ;
//二进制优化
i = 1 ;
while(g>=i)
{
val[count++] = i * v ;
g -= i ;
i *= 2 ;
}
if(g) val[count++] = v * g ;
}
//01背包求解
for(i=0; i<count; i++)
{
for(j=cash; j>=val[i]; j--)
{
dp[j] = Max(dp[j], dp[j-val[i]]+val[i]) ;
}
}
printf("%d\n", dp[cash]) ;
}
return 0 ;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/d_x_d/article/details/47842349