HDU 1203 和 HDU 2191

HDU 1203题:http://acm.hdu.edu.cn/showproblem.php?pid=1203
HDU2191题:http://acm.hdu.edu.cn/showproblem.php?pid=2191
1023是一个01背包,2191是一个完全背包问题。
困惑我的问题是:这两个题有相似的地方,但相似的地方又有不一样,那个不一样的地方正是困扰我的关键所在。
他们的dp一开始都要赋初值,因为要求的是求最小值,那么dp便赋值成题中的最大。
但1023的dp是从0到n赋值,2191是从1赋值到n。
long long ago。。。。。。
我想到了一个点,不知对不对。
第一:他们是不同的背包啊,根据他们自身的性质(我这里就不细说了,参考:http://blog.csdn.net/zxy160/article/details/54378762),确实应该这样赋值;
第二:我认为根据题意也有关系(实在没办法了,就只能根据题意来判断了)。
代码就不注释了,看看就懂了吧!如果不懂:http://blog.csdn.net/zxy160/article/details/54378762
哈哈哈哈哈,就这样吧!

1203
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int M = 10005;
int v[10005];
double f[10005],w[10005];
int main()
{
    int m,n;
    while(~scanf("%d%d",&m,&n))
    {
        int i,j;
        if(m==0&&n==0)
            break;
        memset(f,0,sizeof(f));
        for(i=1; i<=n; i++)
        {
            int a1;
            double a2;
            scanf("%d%lf",&v[i],&w[i]);
            w[i]=1-w[i];
        }
        for(i=0; i<=10005; i++)
            f[i]=1;
        for(i=1; i<=n; i++)
        {
            for(j=m; j>=v[i]; j--)
            {
                f[j]=min(f[j],f[j-v[i]]*w[i]);
            }
        }
        f[m]=(1-f[m])*100;
        printf("%.1lf%%
",f[m]);
    }
    return 0;
}
2191
#include<string.h>
#include<algorithm>
#include<iostream>
using namespace std;
int main()
{
    int t,n,m,i,j,v[111],w[111],c[111],dp[111];
    int count,V1[1111],W1[1111];
    cin>>t;
    while(t--)
    {
        count=0;
        cin>>n>>m;
        for(i=0; i<m; i++)
        {
            cin>>v[i]>>w[i]>>c[i];
            for(j=1; j<=c[i]; j<<=1)
            {
                V1[count]=j*v[i];
                W1[count++]=j*w[i];
                c[i]-=j;
            }
            if(c[i]>0)
            {
                V1[count]=c[i]*v[i];
                W1[count++]=c[i]*w[i];
            }
        }
        memset(dp,0,sizeof(dp));
        for(i=0;i<count;i++)
            for(j=n;j>=V1[i];j--)
            dp[j]=max(dp[j],dp[j-V1[i]]+W1[i]);
        cout<<dp[n]<<endl;
    }
    return 0;
}
"No regrets."
原文地址:https://www.cnblogs.com/zxy160/p/7215175.html