p1473 Zero Sum

搜索,最后判断一下是否结果为0就行。

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <cstring>
#include <map>
#include <queue>
#include <set>
#include <cassert>
#include <stack>
#include <bitset>
#define mkp make_pair
using namespace std;
const double EPS=1e-8;
typedef long long lon;
const lon SZ=200030,INF=0x7FFFFFFF,mod=9901;
char arr[]={'+','-',' '};
vector<string> res;

int cal(string str)
{
    int pos=0;
    pos=str.find_first_of("+-",pos);
    if(pos==-1)return 123456789;
    int ope1=0,ope2=0;
    for(int i=0;i<pos;++i)
    {
        if(str[i]!=' ')
        {
            ope1=ope1*10+str[i]-'0';
        }
    }
    int oldpos=++pos;
    for(;;)
    {
        pos=str.find_first_of("+-",oldpos);
        if(pos==-1)pos=str.size();
        for(int i=oldpos;i<pos;++i)
        {
            if(str[i]!=' ')
            {
                ope2=ope2*10+str[i]-'0';
            }
        }
        if(str[oldpos-1]=='+')ope1=ope1+ope2,ope2=0;
        else ope1=ope1-ope2,ope2=0;
        oldpos=pos+1;
        if(pos==str.size())break;
    }
    return ope1;
}

void dfs(int pos,int n,string &str)
{
    if(pos==n+1)
    {
        if(cal(str)==0)
        {
            res.push_back(str);
        }
        return;
    }
    for(int i=0;i<3;++i)
    {
        str+=arr[i];
        str+=pos+'0';
        dfs(pos+1,n,str);
        str.erase(str.end()-2,str.end());
    }
}

int main()
{
    std::ios::sync_with_stdio(0);
    //freopen("d:\\1.txt","r",stdin);
    lon casenum;
    //cin>>casenum;
    //for(lon time=1;time<=casenum;++time)
    {
        int n;
        cin>>n;
        string str="1";
        dfs(2,n,str);
        sort(res.begin(),res.end());
        for(int i=0;i<res.size();++i)
        {
            cout<<res[i]<<endl;
        }
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/gaudar/p/9826491.html