蓝桥杯-带分数-dfs

100 可以表示为带分数的形式:100=3+69258/714
注意特征:带分数中,数字 1∼9 分别出现且只出现一次(不包含 0)。

类似这样的带分数,100 有 11 种表示法。

输入格式
一个正整数。

输出格式
输出输入数字用数码 1∼9 不重复不遗漏地组成带分数表示的全部种数。

数据范围
1≤N<106
输入样例1:
100
输出样例1:
11
输入样例2:
105
输出样例2:
6

做法 :先枚举右边式子的整数a,再枚举右边分母c, 可得b = nc - ac 然后将b分解对应存入st,进行判断。

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>

using namespace std;

typedef long long ll;

const int N = 10;

int n,ans;
bool st[N], backup[N];

bool check(int a, int c){
	ll b = n *(ll)c - a * c;
	if(!a || !b || !c) return false;
	memcpy(backup, st, sizeof st);
	
	while(b){
		int x = b % 10;
		b /= 10;
		if(!x || backup[x]) return false;
		backup[x] = true;
	}
	for(int i = 1; i <= 9; i++){
		if(!backup[i]){
			return false;
		}
	}
	return true;
} 

void dfs_c(int u, int a, int c){
	if(check(a,c)) ans++;
	for(int i = 1; i <= 9; i++){
		if(!st[i]){
			st[i] = true;
			dfs_c(u + 1, a , c * 10 + i);
			st[i] = false;
		}
	}
}

void dfs_a(int u, int a){
	if(a >= n) return;
	if(a) dfs_c(u,a,0);
	for(int i = 1; i <= 9; i++){
		if(!st[i]){
			st[i] = true;
			dfs_a(u + 1, a * 10 + i);
			st[i] = false;
		}
	}
} 

int main(){
	cin >> n;
	dfs_a(0,0);
	cout << ans << endl; 
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值