ACM PKU 1276 Cash Machine http://acm.pku.edu.cn/JudgeOnline/problem?id=1276

大家都过了,我也来凑热闹了!最简单的01背包(也可以说是完全背包)!我将它01化了,很简单;代码在下面,有什么不懂的可以来问我!欢迎大家提问:

#include <iostream>
using namespace std;

int flag[1100000];
int sign[1100000];


inline int max(int a, int b)
{
    return a > b ? a : b ; 
}

int Dp (int cash, int index)
{
    int i, j;
    memset(sign,0,sizeof(sign));
    for (i = 0; i <= index; i++)
        for (j = cash; j >= flag[i]; j--)
        {
            sign[j] = max(sign[j],sign[j-flag[i]]+flag[i]);
        }
        return sign[cash];        
}

int main()
{
    int cash,n;
    while(scanf("%d%d",&cash,&n) != EOF)
    {
        int index = 0 ; 
        int num , temp ;
        for (int i = 0;i < n; i++)
        {
            int pow = 1; 
            scanf("%d%d",&num,&temp);
            
            while(1)
            {
                if( pow >= num )
                {
                    flag[index++] = temp * num;
                    break;
                }
                else 
                {
                    flag[index++] = temp * pow;
                    num = num - pow;
                    pow *= 2 ; 
                }
            }
        }
        cout << Dp(cash,index-1) <<endl;
    }
    return 0;
}

posted on 2011-05-06 18:44  _Clarence  阅读(97)  评论(0编辑  收藏

导航

统计