codeforces 1036C
题意:
给 定 区 间 [ l , r ] , 限 制 条 件 : 给定区间[l,r],限制条件: 给定区间[l,r],限制条件:
- 所 有 数 位 上 不 为 0 的 数 不 超 过 3 个 所有数位上不为0的数不超过3个 所有数位上不为0的数不超过3个
问 区 间 内 满 足 以 上 条 件 的 数 的 个 数 。 问区间内满足以上条件的数的个数。 问区间内满足以上条件的数的个数。
题解:
d p [ p o s ] [ c n t ] 表 示 查 找 到 第 p o s 位 , 截 止 当 前 位 的 非 零 数 的 个 数 为 c n t 的 数 的 个 数 。 dp[pos][cnt]表示查找到第pos位,截止当前位的非零数的个数为cnt的数的个数。 dp[pos][cnt]表示查找到第pos位,截止当前位的非零数的个数为cnt的数的个数。
- 记 忆 化 搜 索 , d f s ( p o s − 1 , c n t + ( i = = 0 ? 0 : 1 ) , l e a d & & i = = 0 , l i m i t & & i = = b i t [ p o s ] ) 记忆化搜索,dfs(pos-1, cnt+(i == 0 ? 0 : 1), lead \&\& i == 0, limit \&\& i == bit[pos]) 记忆化搜索,dfs(pos−1,cnt+(i==0?0:1),lead&&i==0,limit&&i==bit[pos])
#include <bits\stdc++.h>
using namespace std;
typedef long long ll;
int bit[20];
ll dp[20][1<<7];
ll dfs(int pos, int cnt, bool lead, bool limit){
if(pos == 0){
return cnt <= 3;
}
if(!limit && !lead && dp[pos][cnt] != -1){
return dp[pos][cnt];
}
int up = (limit ? bit[pos] : 9);
ll res = 0;
for(int i = 0 ; i <= up ; i++){
res += dfs(pos-1, cnt+(i == 0 ? 0 : 1), lead && i == 0, limit && i == bit[pos]);
}
if(!limit && !lead){
dp[pos][cnt] = res;
}
return res;
}
ll count(ll x){
int len = 0;
while(x){
bit[++len] = x%10;
x /= 10;
}
return dfs(len, 0, true, true);
}
int main() {
int t;
memset(dp, -1, sizeof(dp));
for(cin >> t ; t > 0 ; t--){
ll l, r;
cin >> l >> r;
cout << count(r)-count(l-1) << endl;
}
return 0;
}