动态规划01背包问题c++

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

#include
#include

using std::cout;
using std::endl;
using std::ifstream;

const char* file_in="/home/yuanzhen/C_script/01beibao/beibao0.in";
const int max_people=10000;
const int max_mine=100;

int mine;
int peopleTotal;
int peopleNeed[max_mine];
int Gold[max_mine];
int sumGold[max_people][max_mine];

void init()
{
    cout << file_in << endl;
    ifstream inputFile(file_in);

    inputFile >> peopleTotal >> mine;

    for (int i=0;i       inputFile >> peopleNeed[i] >> Gold[i];

    for(int i=0;i       for(int j=0;j         sumGold[i][j]=-1;

    inputFile.close();
}

int getMaxGold(int people, int mineNum)
{
    int totalGold;
    if(sumGold[people][mineNum]!=-1)
      //return sumGold[people][mineNum];
      totalGold=sumGold[people][mineNum];
    else if(mineNum==0)
    {
        if(people>=peopleNeed[mineNum])
          totalGold=Gold[mineNum];
        else
        {
            totalGold=0;
        }
    }
    else
    {
        if(people>=peopleNeed[mineNum])
          totalGold=std::max(getMaxGold(people, mineNum-1), getMaxGold(people-peopleNeed[mineNum],mineNum-1)+Gold[mineNum]);
        else
          totalGold=getMaxGold(people, mineNum-1);
    }
    sumGold[people][mineNum]=totalGold;
    return totalGold;
}

int main(int argc, char** argv)
{
    init();

    cout << "peopleTotal" << "\t" << peopleTotal << endl;
    cout << "mine" << "\t" << mine << endl;
    cout << "peopleNeed\t" ;
    for(int i=0;i       cout << peopleNeed[i] << "\t";
    cout << endl;

    cout << "Gold\t";
    for(int i=0;i       cout << Gold[i] << "\t";
    cout << endl;

    int result=getMaxGold(peopleTotal, mine);
    cout << "result\t" << result << endl;
}
 

转载于:https://my.oschina.net/lCQ3FC3/blog/833897

你可能感兴趣的:(动态规划01背包问题c++)