思路:
所有的數位dp長一個模樣。
考慮一下,在某一位上的往下遞歸,可能和哪幾個條件有關。
1.位數
2.前一位的值
3.當前是奇數位還是偶數位。
* 注意前導零的時候後,默認pre是最大值9。
根據數位dp模板即可寫出
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
int digits[22];
int dp[22][10][2];
int dfs( int pos,int pre0,int isOdd,int pre,int limit) {
if ( pos<0 ) return 1;
if ( !limit && dp[pos][pre][isOdd]!=-1 )
return dp[pos][pre][isOdd];
int ans = 0 ;
int last = limit ? digits[pos] :9;
for ( int i=0; i<=last; i++ ) {
if ( pre0 && i==0 )
ans+=dfs( pos-1,1,isOdd,pre,0 );
else {
if ( isOdd && i>=pre )
ans += dfs( pos-1 ,0, 0 , i , limit&&i==last );
if ( (!isOdd )&& i<=pre )
ans += dfs( pos-1 ,0, 1 , i , limit&&i==last );
}
}
if ( !limit )
dp[pos][pre][isOdd] = ans;
return ans;
}
int judge( int x) {
int cnt = 0 ;
while ( x ) {
digits[cnt] = x%10;
x /= 10;
cnt++;
}
return dfs( cnt-1 ,1 , 0 , 9, 1 );
}
int main()
{
int T;
scanf("%d",&T);
memset( dp,-1,sizeof dp );
while ( T-- ) {
int l,r;
cin>>l>>r;
cout<<judge(r)-judge(l-1)<<endl;
}
return 0;
}