C++ mixed number (recursion, enumeration, nested deep search)

100 can be expressed as a mixed number: 100=3+69258/714
can also be expressed as: 100=82+3546/197
Note feature: In a mixed number, the numbers 1 to 9
appear separately and only once (not including 0) .
For mixed numbers like this, there are 11 representations for 100.
Input format
A positive integer.
Output format The
output and input digits
are composed of numbers 1 to 9 without repetition and no omission to form all the numbers represented by mixed numbers.
Data range
1≤N<106
Input sample 1:
100
Output sample 1:
11
Input sample 2:
105
Output sample 2:
6

#include<iostream>
#include<string.h>

using namespace std;

int N;
bool g[20],backup[20];
long long ans=0;

bool check(int a,int c)//检查a和c是否合法
{
    
    
    int b=N*c-a*c;
    if(!a||!b||!c) return false;
    memcpy(backup,g,sizeof(g));
    int x;
    while(b)
    {
    
    
        x=b%10;//数字重了就不合法
        if(!x||backup[x]) return false;
        b/=10;
        backup[x]=true;
    }
    for(int i=1;i<=9;++i)//少一个数字没出现就不合法
        if(!backup[i]) return false;
    return true;
}

void dfs_c(int n,int a,int c)
{
    
    
    if(n>=9) return;//已经用了9个数字就绝对不合法
    if(check(a,c)) ++ans;

    for(int i=1;i<=9;++i)
        if(!g[i]){
    
    
            g[i]=true;
            dfs_c(n+1,a,c*10+i);
            g[i]=false;
        }
}

void dfs_a(int n,int a)
{
    
    
    if(a>=N) return;//a必须比N小,给b,c留数字
    
    if(a) dfs_c(n,a,0);

    for(int i=1;i<=9;++i)
        if(!g[i]){
    
    
            g[i]=true;
            dfs_a(n+1,a*10+i);
            g[i]=false;
        }
}

int main()
{
    
    
    cin>>N;
    dfs_a(0,0);//用了0个数字,a当前是0
    cout<<ans;
}

Guess you like

Origin blog.csdn.net/qq_44643644/article/details/108898250