题目链接:http://codeforces.com/contest/1036/problem/C
题意:求某区间,位数的数字非零并且不超过3个的个数;
思路:
除了数位dp外,可以通过dfs把所有满足条件的数字求出来,然后二分求出个数;
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<queue>
#include<map>
#include<stack>
#include<sstream>
#include<vector>
#include<string>
#include<set>
using namespace std;
#define IOS ios::sync_with_stdio(false); cin.tie(0);
#define REP(i,n) for(int i=0;i<n;++i)
#define lowbit(x) x&(-x)
int read(){
int r=0,f=1;char p=getchar();
while(p>'9'||p<'0'){if(p=='-')f=-1;p=getchar();}
while(p>='0'&&p<='9'){r=r*10+p-48;p=getchar();}return r*f;
}
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<long long,long long> pll;
const int Maxn = 2e5+10;
const int INF = 0x3f3f3f3f;
const long long LINF = 1e18;
const int Mod = 10001;
const double PI = acos(-1.0);
vector <ll> a;
void dfs (int deep,ll num,int n) {
a.push_back(num);
if(deep == 18) return;
dfs(deep+1,num*10,n);
if(n < 3) {
for (int i = 1; i < 10; ++i) {
dfs(deep+1,num*10+i,n+1);
}
}
}
int main (void)
{
IOS;
for (int i = 1; i < 10; ++i) dfs(1,i,1);
a.push_back(1e18);
sort(a.begin(),a.end());
int t;
ll L,R;
cin >> t;
while (t--) {
cin >> L >> R;
int ans = upper_bound(a.begin(),a.end(),R)-lower_bound(a.begin(),a.end(),L);
cout << ans << endl;
}
return 0;
}
数位dp:(直接套数位dp的模板就行了)
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<queue>
#include<map>
#include<stack>
#include<sstream>
#include<vector>
#include<string>
#include<set>
using namespace std;
#define IOS ios::sync_with_stdio(false); cin.tie(0);
#define REP(i,n) for(int i=0;i<n;++i)
#define lowbit(x) x&(-x)
int read(){
int r=0,f=1;char p=getchar();
while(p>'9'||p<'0'){if(p=='-')f=-1;p=getchar();}
while(p>='0'&&p<='9'){r=r*10+p-48;p=getchar();}return r*f;
}
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<long long,long long> pll;
const int Maxn = 2e5+10;
const int INF = 0x3f3f3f3f;
const long long LINF = 1e18;
const int Mod = 10001;
const double PI = acos(-1.0);
int a[20],dp[20][20][5];
int dfs (int cur,int last,int num,bool limit) { // cur当前位数的位置,last当前数的前一个数的值
if(cur < 1 && num <= 3) return 1; // num 位数数字大于0的个数,limit限制条件
if(num > 3) return 0;
if(!limit && dp[cur][last][num] != -1) return dp[cur][last][num];
int End = limit ? a[cur] : 9;
int ret = 0;
for (int i = 0; i <= End; ++i) {
ret+=dfs(cur-1,i,num+(i ? 1 : 0),limit && (i == End));
}
if(!limit) dp[cur][last][num] = ret;
return ret;
}
int solve (ll x) {
int cnt = 0;
while (x) {
a[++cnt] = x%10;
x/=10;
}
return dfs(cnt,-1,0,1);
}
int main (void)
{
IOS;
int t;
ll L,R;
cin >> t;
while (t--) {
memset(dp,-1,sizeof(dp));
cin >> L >> R;
cout << solve(R)-solve(L-1) << endl;
}
return 0;
}