Problem 2109 Mountain Number
Accept: 67 Submit: 176
Time Limit: 1000 mSec Memory Limit : 32768 KB
Problem Description
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).
Output
For each test case, output the number of "Mountain Number" between L and R in a single line.
Sample Input
31 101 1001 1000
Sample Output
954384
//看别人的代码打的,果然多的思维太弱了,留着以后琢磨
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define N 15
int f[2][N][N],a[N];
int dfs(int pos,int pre,int k,int isFirst,int isEnd){isEnd为边界
if(pos<0)return 1;
if(isEnd==0&&f[k][pos][pre]!=-1)return f[k][pos][pre];
int res=0;
int n=9;
if(isEnd)n=a[pos];//比如1234 pos=2,可以999但pos=1只能到1234
for(int i=0;i<=n;i++){
if(isFirst&&i==0)res+=dfs(pos-1,9,0,1,0);//前导0,isFirst不变
else if(k&&i>=pre)res+=dfs(pos-1,i,k^1,0,isEnd&&i==n);//k=1,当前为奇
else if(k==0&&i<=pre)res+=dfs(pos-1,i,k^1,0,isEnd&&i==n);
}
if(isEnd==0)f[k][pos][pre]=res;
return res;
}
int dp(int n){
int i;
for(i=-1;n;n/=10)a[++i]=n%10;
memset(f,-1,sizeof(f));
return dfs(i,9,0,1,1);
}
int main(){
int T,l,r;
scanf("%d",&T);
while(T--){
scanf("%d%d",&l,&r);
printf("%d\n",dp(r)-dp(l-1));
}
return 0;
}