我用C++ class结构,写了个关于第三题的程序。楼主可以参考。
#include
#include
#include
#include
#include
using namespace std;
//Constructor use -1 to terminate parameter;
//like CalcMoney(100,1,2,5,-1);
class CalcMoney
{
friend int main(int argc,char *argv[]); //use for debug
private:
int nWays;
int TotalMoney;
int size;
vector vMoney;
vector vMaxCount;
vector vCount;
protected:
void DisplayMoney();
public:
CalcMoney(int,int,...);
void PutThingsTogether();
void Init();
void DoTheSort();
void CalcMaxCount();
void Calculate(int level,int sum);
int Show();
};
CalcMoney::CalcMoney(int Money=100,int first=1,...)
{
size=1;
va_list pos;
int argument;
TotalMoney=Money;
vMoney.push_back(first);
va_start(pos,first);
while( (argument=va_arg(pos,int))!=-1 )
{
vMoney.push_back(argument);
size++;
}
}
void CalcMoney::PutThingsTogether()
{
Init();
DoTheSort();
CalcMaxCount();
cout << "The total money is: " << TotalMoney << "\n";
cout << "The change is: \n";
for(int i=0;i cout << vMoney[i] << "\t";
cout << "\n";
cout << "----------------------------";
cout << endl;
Calculate(0,0);
}
void CalcMoney::Init()
{
vCount.resize(size);
nWays=0;
}
void CalcMoney::DoTheSort()
{
sort(vMoney.begin(),vMoney.end(),greater());
}
void CalcMoney::CalcMaxCount()
{
for(int i=0;i vMaxCount.push_back(TotalMoney/vMoney[i]);
}
void CalcMoney::Calculate(int level,int sum)
{
int PartSum;
if(level==size)
return;
for(int i=0;i<=vMaxCount[level];i++)
{
vCount[level]=i;
PartSum=i*vMoney[level];
if(sum+PartSum==TotalMoney)
{
nWays++;
//print the result
for(int j=0;j<=level;j++)
cout << vCount[j] << "\t";
cout << endl;
continue;
}
Calculate(level+1,sum+PartSum);
}
}
void CalcMoney::DisplayMoney()
{
vector::iterator iter;
for(iter=vMoney.begin();iter!=vMoney.end();iter++)
cout << *iter << "\n";
cout << endl;
}
int CalcMoney::Show()
{
return nWays;
}
int main(int argc,char *argv[])
{
CalcMoney cm(100,1,2,5,-1);
cm.PutThingsTogether();
cout << "There are " << cm.Show() << " ways." << endl;
return 0;
}
事实上以上程序,最重要的是Calculate()递归函数。如果按C的风格,只要这个函数就OK了。但是为了练习一下C++,呵呵。如果有疑问可以提出。声明一下,我不是C++高手。进来纯属好奇。
--------------------next---------------------
阅读(973) | 评论(0) | 转发(0) |