Educational Codeforces Round 50 (Rated for Div. 2) C. Classy Numbers(dfs或者数位dp)

题目大意:数字中非0数字少于3的数被称为Classy number,给出一个区间l,r,输出在这个区间内的classy number
题目链接:http://codeforces.com/contest/1036/problem/C
思路:两种:
一种是使用dfs找出所有小于1e18的classy number,再用二分法搜索在范围内的数,第二种是使用数位dp的模板,细节看代码吧
c++ 代码:
dfs+二分:

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

typedef long long LL;


vector <LL> v;

void dfs(LL cur,LL cnt,LL len) {
	v.push_back(cur);
	if(len==18)return;
	dfs(cur*10,cnt,len+1);//先考虑第len位是0的情况 
	for(int i=1;i<=9;i++)
	     if(cnt<3) {
	     	dfs(cur*10+i,cnt+1,len+1);
		 }
}

int main() {
    int T;
	for(LL i=1;i<=9;i++)
	    dfs(i,1,1);
	v.push_back(1e18);
	sort(v.begin(),v.end());
	cin >> T;
	while(T--) {
		LL l,r;
		cin >> l >> r;
		int x=lower_bound(v.begin(),v.end(),l)-v.begin();
		int y=upper_bound(v.begin(),v.end(),r)-v.begin();
		cout << y-x <<endl;
	}
	return 0;
}

数位dp:

#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>

using namespace std;

typedef long long LL;
//递推用的是1,2,3所以开4个状态 
LL dp[20][4];//储存没有数位限制的情况下某一位在某一状态下可生成的数的数量 
LL a[20];


LL dfs(int pos,int sta,bool lim) {
	if(sta>3)return 0;
	if(pos==-1)return 1;
	if(!lim&&dp[pos][sta]!=-1)return dp[pos][sta];//如果没有数位限制则每个选择的结果数相等 
	//如果有位数限制则需要额外计算 
	LL up=lim?a[pos]:9;//判断是否有最高位限制 
	LL ans=0;
	for(LL i=0;i<=up;i++) {
		ans+=dfs(pos-1,sta+(i>0),lim&&(up==i));
	}
	if(!lim)dp[pos][sta]=ans;//本层递推完成 
	//最高位达到限制的不用更新数组,直接返回结果到上一层
	return ans; 
}

LL solve(LL x) {
	 int pos=0;
	memset(dp,-1,sizeof(dp));
	while(x) {
		a[pos++]=x%10;
		x/=10;
	}
	//cout <<"p" <<pos <<endl;
	//LL y;
	//cout << (y=) <<endl;
	return dfs(pos-1,0,1);
}




int main() {
    int T;
	cin >> T;
	while(T--) {
		LL l,r;
		cin >> l >> r;
		memset(a,0,sizeof(a));
		cout << solve(r)-solve(l-1)<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_39475280/article/details/82891232