洛谷 - P1149 - 火柴棒等式 - dfs

https://www.luogu.org/problemnew/show/P1149

一开始还分类重复了。在非0的dfs中居然赋值了0,脑残得一笔。

其实就按lead0分类就好了,lead0表示当前位有没有被赋值过,只有没被赋值过的赋值前导0才会立刻进入下一个数字。

#include<bits/stdc++.h>
using namespace std;
#define ll long long

int cost[]={6,2,5,5,4,5,6,3,7,6};

int cnt=0;

set<pair<pair<ll,ll>,ll> >s;

void dfs(int i,int n,ll a,ll b,ll c,int lead0){
    if(n<0)
        return;
    //cout<<"i="<<i<<" "<<a<<" + "<<b<<" = "<<c<<" restn= "<<n <<endl;
    //lead0=1,表示这个数可以取前导0,也就是这个数还没有被赋值
    if(i==1){
        if(lead0){
            if(n-cost[0]>=0)
                dfs(2,n-cost[0],0,b,c,1);
                //给a赋值0,那么a就不能搜索了
            for(int i=1;i<=9;i++){
                //这个bug服气了,非零居然从0开始
                if(n-cost[i]>=0){
                    dfs(1,n-cost[i],i,b,c,0);
                    //给a赋值非0
                }
            }
        }
        else{
            //a已经被赋值过非0了

            //停止搜索a,考虑b,b没被赋值
            dfs(2,n,a,b,c,1);

            for(int i=0;i<=9;i++){
                if(n-cost[i]>=0){
                    dfs(1,n-cost[i],a*10+i,b,c,0);
                    //继续给a加后缀
                }
            }
        }
    }
    else if(i==2){
        if(lead0){
            //进不来这里,改了之后就可以进来了
            dfs(3,n-cost[0],a,0,c,1);
            //给b赋值0,那么b就不能搜索了
            for(int i=1;i<=9;i++){
                if(n-cost[i]>=0){
                    dfs(2,n-cost[i],a,i,c,0);
                    //给b赋值非0
                }
            }
        }
        else{
            //b已经被赋值过非0了

            //停止搜索b,考虑c
            dfs(3,n,a,b,c,1);

            for(int i=0;i<=9;i++){
                if(n-cost[i]>=0){
                    dfs(2,n-cost[i],a,b*10+i,c,0);
                    //继续给b加后缀
                }
            }
        }
    }
    else if(i==3){
        if(lead0){
            //进不来这里?
            dfs(4,n-cost[0],a,b,0,1);
            //给c赋值0,那么c就不能搜索了
            for(int i=1;i<=9;i++){
                if(n-cost[i]>=0){
                    dfs(3,n-cost[i],a,b,i,0);
                    //给c赋值非0
                }
            }
        }
        else{
            //停止搜索c
            dfs(4,n,a,b,c,1);
            //c已经被赋值过非0了
            for(int i=0;i<=9;i++){
                if(n-cost[i]>=0){
                    dfs(3,n-cost[i],a,b,c*10+i,0);
                    //继续给c加后缀
                }
            }
        }
    }
    else{
        if(n==0&&(a+b==c)){
            s.insert({{a,b},c});
            cnt++;
        }
        return;
    }
}


int main(){
    int n;
    scanf("%d",&n);
    n-=4;
    dfs(1,n,-1,-1,-1,1);
    printf("%d\n",s.size());
}

猜你喜欢

转载自www.cnblogs.com/Yinku/p/10314521.html
今日推荐