1209. 带分数(DFS)

1209. 带分数

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

int num[10], n;
bool st[10];
int res;

int calc(int l, int r){
    int res = 0;
    for(int i = l; i <= r; ++i) res = res * 10 + num[i];
    return res;
}

void dfs(int u){
    if(u == 10){
            for(int i = 1; i < 8; ++i){
            for(int j = i + 1; j <= 8; ++j){
                int a = calc(1, i);
                int b = calc(i + 1, j);
                int c = calc(j + 1, 9);
                if(n * c == a * c + b) ++res;
            }
        }
    }
    
    for(int i = 1; i <= 9; ++i){
        if(!st[i]){
            st[i] = true;
            num[u] = i;
            dfs(u + 1);
            st[i] = false;
        }
    }
}
signed main(){
    for(int i = 1; i <= 9; ++i) num[i] = i;
    cin >> n;
    
    dfs(1);
    
    cout << res << endl;
    
    
    return 0;
}

next_permutation

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

int num[10], n;

int calc(int l, int r){
    int res = 0;
    for(int i = l; i <= r; ++i) res = res * 10 + num[i];
    return res;
}
signed main(){
    for(int i = 1; i <= 9; ++i) num[i] = i;
    cin >> n;
    int res = 0;
    do{
        for(int i = 1; i < 8; ++i){
            for(int j = i + 1; j <= 8; ++j){
                int a = calc(1, i);
                int b = calc(i + 1, j);
                int c = calc(j + 1, 9);
                if(n * c == a * c + b) ++res;
            }
        }
        
    }while(next_permutation(num + 1, num + 10));
    
    cout << res << endl;
    
    
    return 0;
}
posted @ 2025-03-28 17:37  awei040519  阅读(17)  评论(0)    收藏  举报