24點

#include<bits/stdc++.h>
using namespace std;
const double inf=1e10;
const double eps=1e-5;
int aim;
bool equal(double x,double y){return x>y-eps&&x<y+eps;}
struct Expression
{
    string exp;
    double val;
    Expression()
    {
        exp.clear();
        val=0;
    }
    Expression(int x)
    {
        val=(double)x;
        exp.clear();
        if(x==0)exp+='0';
        while(x)
        {
            exp+=x%10+'0';
            x/=10;
        }
        reverse(exp.begin(),exp.end());
    }
    bool operator < (const Expression &x)const
    {
        int cmp=exp.compare(x.exp);
        return cmp<0||(cmp==0&&val<x.val);
    }
};
Expression merge(Expression x,char c,Expression &y)
{
    x.exp+=c;
    x.exp+=y.exp;
    x.exp.insert(x.exp.begin(),'(');
    x.exp+=')';
    if(c=='+')x.val+=y.val;
    else if(c=='-')x.val-=y.val;
    else if(c=='*')x.val*=y.val;
    else x.val/=y.val;
    return x;
}
void list_all(vector<Expression> &ret,Expression &x,Expression &y)
{
    ret.push_back(merge(x,'+',y));
    ret.push_back(merge(x,'*',y));
    ret.push_back(merge(x,'-',y));
    ret.push_back(merge(y,'-',x));
    if(!equal(y.val,0))ret.push_back(merge(x,'/',y));
    if(!equal(x.val,0))ret.push_back(merge(y,'/',x));
}
set<Expression> ans;
void solve(vector<Expression> &v)
{
    int n=v.size(),i,j,k;
    if(n==1)
    {
        if(equal(v[0].val,aim))ans.insert(v[0]);
        return;
    }
    for(i=0;i<n-1;++i)
        for(j=i+1;j<n;++j)
        {
            vector<Expression> all,nxt;
            list_all(all,v[i],v[j]);
            for(k=0;k<n;++k)
                if(k!=i&&k!=j)nxt.emplace_back(v[k]);
            for(k=0;k<all.size();++k)
            {
                nxt.emplace_back(all[k]);
                solve(nxt);
                nxt.pop_back();
            }
        }
}
int main()
{
    ios::sync_with_stdio(false);
    int x,cnt=0;
    vector<Expression> para;
    while(cin>>x)
    {
        if(x<0)
        {
            aim=-x;
            ans.clear();
            solve(para);
            cout<<"solution:\n";
            for(auto &x : ans)cout<<x.exp<<" = "<<x.val<<endl;
            cout<<"end of solution\n";
            para.clear();
        }
        else para.emplace_back(x);
    }
}
相關文章
相關標籤/搜索