#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
#define N 100
template<class Type>
class SeqStack
{
public:
SeqStack(int size);
~SeqStack();
bool isempty() const;
bool isfull() const;
void Push(Type &e);
void Print();
void Pop();
Type GetTop();
private:
int maxsize;
Type *base;
int top;
};
template<class Type>
bool SeqStack<Type>::isfull() const
{
return top == maxsize;
}
template<class Type>
bool SeqStack<Type>::isempty() const
{
return top == 0;
}
template<class Type>
SeqStack<Type>::SeqStack(int size):maxsize(size)
{
base = new Type[maxsize];
if (base == NULL)
{
cout<<"·ÖÅäÄÚ´æʧ°Ü";exit(0);
}
top = 0;
}
template<class Type>
void SeqStack<Type>::Push(Type &e)
{
if (isfull())
{
cout<<"Õ»¿Õ¼äÒÑÂú"<<endl;
exit(0);
}
else base[top++] = e;
}
template<class Type>
void SeqStack<Type>::Pop()
{
if (isempty())
{
cout<<"ջΪ¿Õ"<<endl;exit(0);
}
else --top;
}
template<class Type>
Type SeqStack<Type>::GetTop()
{
if (isempty())
{
cout<<"ջΪ¿Õ"<<endl;exit(0);
}
else return base[top-1];
}
template<class Type>
void SeqStack<Type>::Print()
{
cout<<"(";
for (int i=0;i<top;i++)
if (i < top-1) cout<<base[i]<<','; else cout<<base[i]<<')'<<endl;
}
template<class Type>
SeqStack<Type>::~SeqStack()
{
delete [] base;
}
int T,n,w[N];
SeqStack<int> S(N);
void Search(int x, int tot)
{
if (tot == T)
{
S.Print();//Êä³öÕ»ÖÐËùÓÐÔªËØ
return ;
}
if (x == n+1) return ;
if (tot + w[x] <= T)
{
S.Push(w[x]);
Search(x+1,tot+w[x]);
S.Pop();
}
Search(x+1,tot);
}
int main()
{
printf("Please input the volunme T of the bag and the number of things n\n");
printf("T = ");scanf("%d", &T);
printf("n = ");scanf("%d", &n);
printf("Please input the volunme w_i of each things\n");
for (int i=1;i<=n;i++)
scanf("%d", &w[i]);
Search(1, 0);
}
回溯
最新推荐文章于 2022-08-23 16:32:29 发布