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) ?
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).
3 1 10 1 100 1 1000
9 54 384
从左至右记为a[0]、a[1]..........a[2*i]、a[2*i+1]......。相邻的奇数位小于等于偶数为的为特殊数。让求区间内特殊数的个数。奇偶还是第一次见到,感觉难点就在这,不过解决起来也是出乎意料的简单。然后就是细节的判断处理,一个模板套出来结果了。
代码如下:
#include <iostream>
#include <cstring>
using namespace std;
typedef long long LL;
int a[100];
LL dp[100][10][2];
// pos pre sta
// 位 前一个 奇偶 前导0 边界
LL dfs(int pos, int pre, int sta, bool lead, bool limit)
{
if (pos == -1)
{
return 1;
}
if (!limit && dp[pos][pre][sta] != -1)
return dp[pos][pre][sta];
int up = limit ? a[pos] : 9;
LL temp = 0;
for (int i = 0; i <= up; i++)
{
if (lead && i == 0) //(i == 0 && lead == 0) //有前导0 且 i = 0
temp += dfs(pos - 1, 9, 0, lead && i == 0, limit && i == up);
else if (sta == 1 && pre <= i)//奇数 且 pre小
temp += dfs(pos - 1, i, 1 - sta, lead && i == 0, limit && i == up);
else if (sta == 0 && pre >= i)//偶数 且 pre大
temp += dfs(pos - 1, i, 1 - sta, lead && i == 0, limit && i == up);
else
{
//cout << "***************" << endl;
}
}
if (!limit)
dp[pos][pre][sta] = temp;
return temp;
}
LL solve(LL x)
{
int pos = 0;
while (x)
{
a[pos++] = x % 10;
x /= 10;
}
return dfs(pos-1, 9, 0, 1, 1);
// pos pre sta lead limit
}
int main()
{
int t;
LL le, ri;
cin >> t;
while (t--)
{
memset(dp, -1, sizeof(dp));
cin >> le >> ri;
cout << solve(ri) - solve(le - 1) << endl;
}
return 0;
}