CSubSet.h
#include "stdafx.h"
#if !defined(_CSUBSET_H_)
#define _CSUBSET_H_
class CSubSet{
private:
std::vector<int> vecWeight;
short *vecFlag;
int cnt, weight;
public:
CSubSet(const char*);
CSubSet(const CSubSet&);
bool init(const char* finname);
bool seekSubset(const char *foutname);
bool _seekSubset(int level, int total);
virtual ~CSubSet();
};
#endif
CSubSet.cc
#include "stdafx.h"
#include "CSubSet.h"
CSubSet::CSubSet(const char* finname){
init(finname);
}
CSubSet::CSubSet(const CSubSet &subset){
vecWeight = subset.vecWeight;
cnt = subset.cnt;
weight = subset.weight;
int len = vecWeight.size();
vecFlag = new short[len];
memset(vecFlag, 0, sizeof(short)*len);
}
bool CSubSet::init(const char* finname){
std::ifstream fin;
fin.open(finname);
if(fin.good()){
int value;
std::string str, token;
std::getline(fin, str);
std::stringstream strStream;
strStream << str;
std::getline(strStream, token, ' ');
cnt = atoi(token.c_str());
std::getline(strStream, token, ' ');
weight = atoi(token.c_str());
std::getline(fin, str);
std::stringstream stream;
stream << str;
while(std::getline(stream, token, ' ')){
value = atoi(token.c_str());
vecWeight.push_back(value);
}
int len = vecWeight.size();
vecFlag = new short[len];
memset(vecFlag, 0, sizeof(short)*len);
}
return true;
}
bool CSubSet::seekSubset(const char *foutname){
std::ofstream fout;
fout.open(foutname);
if(fout.good()){
if(_seekSubset(0, 0)){
int len = vecWeight.size();
for(int t=0; t<len; ++t){
if(vecFlag[t] > 0){
fout<<vecWeight[t]<<" ";
}
}
}
else{
const char *p = "no solution";
fout.write(p, strlen(p));
}
}
return true;
}
bool CSubSet::_seekSubset(int level, int total){
if(level >= cnt){
if(total != weight){return false;}
return true;
}
bool flag = false;
int tw = total + vecWeight[level];
if(tw == weight){
vecFlag[level] = 1;
return true;
}
if(tw < weight){
vecFlag[level] = 1;
flag = _seekSubset(level+1, tw);
if(flag) return true;
}
if(!flag){
vecFlag[level] = 0;
return _seekSubset(level+1, total);
}
return false;
}
CSubSet::~CSubSet(){
if(vecFlag) delete vecFlag;
}
转载于:https://my.oschina.net/u/1434326/blog/190499