完美数
Time Limit: 2000/1000MS (Java/Others)
Memory Limit: 128000/64000KB (Java/Others)
Problem Description
8是中国人很喜欢的一个数字,但是如果有3的存在就变成了38,就不是很好了。。
你能告诉我,在[L, R] 的正整数区间内,要么包含3 要么包含 8 的不同的整数有多少个么?
Input
第一行一个整数T (T ≤ 10000),代表数据的组数
对于每组数据给两个整数 L, R (1 ≤ L ≤ R ≤ 1e9)
Output
对于每组数据,给一个整数为答案。
Sample Input
3 1 100 1 3 8 8
Sample Output
34 1 1
Source
buaads
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
int dp[12][12],t,x,y,a[12];
int dfs(int pos,bool limit,int s){
if(pos == -1) return s ? 1 : 0;
if(!limit && dp[pos][s] != -1) return dp[pos][s];
int up = limit ? a[pos] : 9;
int ans = 0;
for(int i=0; i<=up; i++){
if(i+s==11) continue;
if(i==3) ans += dfs(pos-1, i==up && limit, 3);
else if(i==8) ans += dfs(pos-1, i==up && limit, 8);
else ans += dfs(pos-1, i==up && limit, s);
}
if(!limit) dp[pos][s] = ans;
return ans;
}
int slove(int n){
int pos = 0;
memset(a,0,sizeof a);
while(n){
a[pos++] = n % 10;
n /= 10;
}
return dfs(pos-1, true, 0);
}
int main()
{
memset(dp,-1,sizeof dp);
scanf("%d",&t);
while(t--){
scanf("%d%d",&x,&y);
printf("%d\n",slove(y) - slove(x-1));
}
return 0;
}