简单背包问题(实际上是子集问题)
来源:互联网 发布:鱼眼校正软件 编辑:程序博客网 时间: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);
}
}
- 简单背包问题(实际上是子集问题)
- 子集和问题(背包)
- uva11205 -(简单题) 生成子集问题
- 0-1背包问题(回朔法搜索子集树)
- C# 为啥用invoke,实际上是处理多线程的问题
- 集合的子集 (其实是组合问题)
- HDU2602(简单背包问题)
- 【动态规划】从子集和问题到背包问题
- 子集问题
- 简单背包问题
- 简单的背包问题
- 简单的背包问题
- 简单背包问题
- 简单0.1背包问题
- 简单背包问题
- 简单:01背包问题
- 简单:01背包问题
- 简单:01背包问题
- 简单继承UserDetails
- 关于Oracle中select * from where 的存储过程
- Mercury QuickTestProfessional 9.0试用版下载
- 转 J2SE:JNI:JAVA调用已经存在的动态连接库(dll)
- id,name区别
- 简单背包问题(实际上是子集问题)
- echo 打印彩色字符
- 向DataTable表中添加一行空信息,使DropDownList的第一个选项为空
- 海空神佛的虚伪[注意]
- 充分利用ASP.NET的三种缓存提高站点性能
- 通用ODBC API应用结构概述
- mx
- 使用高效的日志工具—Log4J
- 软件配置管理概念-1,介绍