简单背包问题(实际上是子集问题)

来源:互联网 发布:鱼眼校正软件 编辑:程序博客网 时间:2024/04/28 13:35

从一堆物品weight[1],。。weight[n]中,从中选取若干件放入背包,使其重量恰好为s ,实际上对weight进行全排列,然后只要和为s,即可输出方案。

例如:

How many weight do you want to input..
6
Input 6 weight
3 4 6 5 7 2
Input the total Weight you want..
12
3+4+5 = 12
5+7 = 12
4+6+2 = 12
3+7+2 = 12
Press any key to continue

 

源程序:cpp文件:

#include "Knap.h"

void main()
{
 vector<int>Weight;
 int x;
 int SUM;
 int Count = 0;
 cout<<"How many weight do you want to input.."<<endl;
 cin>>Count;
 cout<<"Input "<<Count<<" weight "<<endl;
 for(int i = 0;i<Count;i++)
 {
  cin>>x;
  Weight.push_back(x);
 }
 cout<<"Input the total Weight you want.."<<endl;
 cin>>SUM;
 Knap(Weight,Weight.size()-1,SUM);
}

 

头文件:Knap.h

#include<iostream>
#include<vector>
#include<string>
using namespace std;

void Delete(vector<int>&Test,int j)
{
 vector<int> Temp;
 for(int i = 0;i<j;i++)
 {
  Temp.push_back(Test[i]);
 }
 for(i = j+1;i<Test.size();i++)
 {
  Temp.push_back(Test[i]);
 }
 while(!Test.empty())
 {
  Test.pop_back();
 }
  Test = Temp;
}
int sum(vector<int> Weight)
{
 int sum = 0;
 for(int i = 0;i<Weight.size();i++)
 {
  sum += Weight[i];
 }
 return sum;
}
//递归算法
void Knap(vector<int> Weight,int n,int SUM)
{
 if(n < 0)
 {
  if(sum(Weight) == SUM)
  {
   for(int i = 0;i<Weight.size()-1;i++)
   {
    cout<<Weight[i]<<"+";
   }
   cout<<Weight[Weight.size()-1]<<" = "<<SUM;
   cout<<endl;
  }
 }
 else
 {
  vector<int>Temp;
  Temp = Weight;
  Delete(Weight,n);
  Knap(Weight,n-1,SUM);
  Weight = Temp;
  Knap(Weight,n-1,SUM);
 }

}

 

 

原创粉丝点击