背包问题及其空间优化

//会MLE 
#include 
#include 
using namespace std;
#define  max(x,y)   (x)>(y)?(x):(y)
#define maxn 1000
#define maxm 100000
unsigned int weight[maxn],value[maxm];
unsigned int f[maxn][maxm];
int main()
{
	int M,N;
	while(cin>>M>>N)
	{
		memset(weight,0,sizeof(weight));
		memset(value,0,sizeof(value));
		memset(f,0,sizeof(f));
		weight[0]=value[0]=0;
		for(int i=1;i<=N;i++)
		{
			cin>>value[i]>>weight[i];
		}
		for(int i=1;i<=N;i++)
		{
			for(int j=0;j<=M;j++)
			{
				if(weight[i]<=j)
				{
					f[i][j]=max(f[i-1][j],f[i-1][j-weight[i]]+value[i]);
				}
				else
				{
					f[i][j]=f[i-1][j];
				}
			}
		}
		cout<
#include 
#include 
using namespace std;
int main()
{
    int T, k;
    int v[305];
    int t[305];
    int f[20010];
    while(~scanf("%d%d", &T, &k))
    {
        getchar();//防止使用scanf输入时的回车对后面的输入造成影响
        v[0] = 0;
        t[0] = 0;
        memset(f, 0, sizeof(f));
        for(int i = 1; i <= k; i++)
            scanf("%d%d", &v[i], &t[i]);
        getchar();
        for(int i = 1; i <= k; i++)
            for(int j = T; j >= t[i]; j--)
                f[j] = max(f[j - t[i]] + v[i], f[j]);
        printf("%d\n", f[T]);
    }
} 

参考背包问题讲解:http://blog.csdn.net/mu399/article/details/7722810

题源:北航OJ051 零崎的补番计划

优化代码参考:http://blog.csdn.net/shizhengtong0829/article/details/50422879


你可能感兴趣的:(算法)