#include <iostream>
#include <fstream>
#include <algorithm>
#include <queue>
using namespace std;
const int MAX = 50;
int a[MAX];
int x[MAX];
int bestx[MAX];
int bestw = 0;
int cw = 0;
int r = 0;
bool backtrack(int i, int n, int c)
{
if(i>n)
{
bestw = cw;
for(int j=1; j<=n; j++)
bestx[j] = x[j];
if(bestw == c)
return true;
else
return false;
}
r -= a[i];
if(cw+a[i] <= c) //搜索左子树
{
x[i] = 1;
cw += a[i];
if(backtrack(i+1, n, c))
return true;
x[i] = 0;
cw -= a[i];
}
if(cw+r >= bestw) //搜索右子树
{
x[i] = 0;
if(backtrack(i+1, n, c))
return true;
}
r += a[i];
return false;
}
int main()
{
ifstream fin("子集和.txt");
cout << "输入集合大学:";
int n;
fin >> n; cout << n;
cout << "\n输入子集和的目标值:";
int c;
fin >> c; cout << c;
cout << "\n输入集合中的元素:\n";
int i;
for(i=1; i<=n; i++)
{
fin >> a[i];
cout << a[i] << " ";
r += a[i];
}
if(!backtrack(1, n, c))
cout << "No Solution!\n";
else
{
cout << "\n子集为:\n" ;
for(i=1; i<=n; i++)
if(bestx[i])
cout << a[i] << " ";
cout << endl;
cout << endl;
}
fin.close();
return 0;
}
子集和问题
最新推荐文章于 2021-11-22 20:20:51 发布