子集和----回溯法

#include<iostream>
using namespace std;
class ziji{
private:
    int *s;
    int *x;
    int y;
    int sum;
    int *m;
    int n;
public:
    void huisu(int t);
    void Set(int n);
    void Input();
    ziji();
};
ziji::ziji()
{
    for(int i=0;i<n;i++){
        m[i]=0;
    }
    n=0;
    sum=0;
    y=0;
    s=NULL;
    x=NULL;
}
void ziji::Set(int n)
{
    this->n=n;
    x=new int[n];
    s=new int[n];
    m=new int[n];
}
void ziji::Input()
{
    cout<<"x[]=";
    for(int i=0;i<n;i++){
        cin>>x[i];
    }
    cout<<"y=";
    cin>>y;
}
void ziji::huisu(int t)
{
    
    if (t>n-1)
    {
        for(int i=0; i<n; i++)s[i]=m[i];
        int h=0;
        for(i=0;i<n;i++)
            h+=x[i]*m[i];
        if (h<=y)
        {
            if(h==y){
                for(i=0;i<n;i++)
                    if(s[i]==1)cout<<x[i]<<endl;
                cout<<"*************"<<endl;
            }
            
        }
    }
        else
        {
            for (int i=0; i<=1; i++)
            { 
                m[t]=i;
                if (i==0)
                    huisu(t+1);
                else
                    if(sum+x[t]<=y){
                        sum=sum+x[t];
                        huisu(t+1);
                        sum=sum-x[t];
                    }
            }
        }
    }

int main(){
    ziji M;
    int n;
    cin>>n;
    M.Set(n);
    M.Input();
    M.huisu(0);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/wanwu_fusu/article/details/83514225