Mountain Number
One integer number x is called "Mountain Number" if:
(1) x>0 and x is an integer;
(2) Assume x=a[0]a[1]...a[len-2]a[len-1](0≤a[i]≤9, a[0] is positive). Any a[2i+1] is larger or equal to a[2i] and a[2i+2](if exists).
For example, 111, 132, 893, 7 are "Mountain Number" while 123, 10, 76889 are not "Mountain Number".
Now you are given L and R, how many "Mountain Number" can be found between L and R (inclusive) ?
Input
The first line of the input contains an integer T (T≤100), indicating the number of test cases.
Then T cases, for any case, only two integers L and R (1≤L≤R≤1,000,000,000).
For each test case, output the number of "Mountain Number" between L and R in a single line.
Sample Input
3 1 10 1 100 1 1000Sample Output
9 54 384
code:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int dp[12][12][2],data[12];
int dfs(int pos,int pre,int parity,int lead,int limit){
if(pos == -1) return 1;
if(!limit && dp[pos][pre][parity] != -1)
return dp[pos][pre][parity];
int ans = 0;
int up = limit ? data[pos] : 9;
for(int i = 0; i <= up; i++){
if(!lead && !i)
ans += dfs(pos-1,9,0,0,limit && (i == up));
else if(parity && i >= pre)
ans += dfs(pos-1,i,parity^1,1,limit && (i == up));
else if(!parity && pre >= i)
ans += dfs(pos-1,i,parity^1,1,limit && (i == up));
}
if(!limit)
dp[pos][pre][parity] = ans;
return ans;
}
int solve(int x){
int pos = 0;
while(x){
data[pos++] = x % 10;
x /= 10;
}
return dfs(pos-1,9,0,0,1);
}
int main(){
int t,left,right;
memset(dp,-1,sizeof(dp));
scanf("%d",&t);
while(t--){
scanf("%d%d",&left,&right);
printf("%d\n",solve(right) - solve(left-1));
}
return 0;
}