回溯

#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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值