dfs暴力+思维 CodeForces - 244 B Codeforces Round #150 (Div. 2) B题

本文介绍了一个有趣的问题,即在给定范围内找出仅由两个不同数字组成的幸运数字的数量。通过使用深度优先搜索(DFS)策略,文章提供了一种有效的方法来解决这个问题,并详细解释了其背后的算法逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Undoubtedly Lucky Numbers

Polycarpus loves lucky numbers. Everybody knows that lucky numbers are positive integers, whose decimal representation (without leading zeroes) contain only the lucky digits x and y. For example, if x = 4, and y = 7, then numbers 47, 744, 4 are lucky.

Let’s call a positive integer a undoubtedly lucky, if there are such digits x and y (0 ≤ x, y ≤ 9), that the decimal representation of number a (without leading zeroes) contains only digits x and y.

Polycarpus has integer n. He wants to know how many positive integers that do not exceed n, are undoubtedly lucky. Help him, count this number.

Input
The first line contains a single integer n (1 ≤ n ≤ 109) — Polycarpus’s number.

Output
Print a single integer that says, how many positive integers that do not exceed n are undoubtedly lucky.


题目大意为给你数字 n ,求在1-n的范围内,只包含两个不同数字的数的个数;

这题比较巧妙的是dfs,每次在数的尾部添加一个数,每次有两种数字可以添加,这样暴力更省时间;

代码:

#include<bits/stdc++.h>
#define ll long long
#define pa pair<int,int>
#define lson k<<1
#define rson k<<1|1
#define inf 0x3f3f3f3f
//ios::sync_with_stdio(false);
using namespace std;
const int N=100100;
const int M=1000100;
const ll mod=1e9+7;
int a[3];
int n;
set<ll>se;
void dfs(ll p){
	for(int i=1;i<=2;i++){
		ll q=p;
		q=q*10+(ll)a[i];
		if(q<=n&&q){
			se.insert(q);
			dfs(q);
		}
	}
}
int main(){
    ios::sync_with_stdio(false);
    cin>>n;
    for(int i=0;i<=9;i++){
    	for(int j=i+1;j<=9;j++){
    		a[1]=i,a[2]=j;
    		dfs(0);
		}
	}
	cout<<se.size()<<endl; 
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值