The digital difference of a positive number is constituted by the difference between each two neighboring digits (with the leading zeros omitted). For example the digital difference of 1135 is 022 = 22. The repeated digital difference, or differential root, can be obtained by caculating the digital difference until a single-digit number is reached. A number whose differential root is 7 is also called July Number. Your job is to tell how many July Numbers are there lying in the given interval [a, b].
Input
There are multiple cases. Each case contains two integers a and b. 1 ≤ a ≤ b ≤ 109.
Output
One integer k, the number of July Numbers.
Sample Input
1 10
Sample Output
1
题解:
题目大意:将一个数字的相邻两位的差(的绝对值)组成一个新的数字,不断重复,如果最后得到7,就称这个数为July Number,比如9024 – 922 – 70 – 7。题目要求1e9范围内给定区间[a, b]里July Number的个数。
这种数字其实不是很多,通过运行结果得到以1-9结尾的个数
1------451156127 2------131145647 3------44286220 4-----14800278 5------4397180
6------1031969 7------160218 8-----13851 9-----256
因此直接先算出所有数存起来排序后,然后二分查找即可,!比如由7出发,可以得到70, 81, 92, 19, 29,从19出发可以得到109, 890,这只要枚举最后以为数字,然后枚举相邻两位的差是正的还是负的,可以简单的写成一个dfs。注意每次都是用已算出的所有数来逆推,而不是用上一轮的结果。
附上AC代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <queue>
#define inf 0x3f3f3f3f
typedef long long ll;
using namespace std;
const int maxn = 1005;
vector<ll> a;
vector<ll> v;
ll di[] = {10,100,1000,10000,100000,1000000,10000000,100000000,1000000000};
int getarr(ll a,int b[])<span style="white-space:pre"> </span>//数字转化为数组
{
int t = 0;
while(a != 0)
{
b[t++] = a%10;
a /= 10;
}
return t-1;
}
ll getnum(int a[],int n)<span style="white-space:pre"> </span>//数组转化为数字
{
ll ans = 0, d = 1;
for(int i = 0;i < n;++i)
{
ans += a[i]*d;
d *= 10;
}
return ans;
}
void dfs(int l,int r,int a[],int tp[])
{
if(l > r-2)
{
ll ans = getnum(tp,r);
if(ans >= di[r-2]){
v.push_back(ans);
}
return;
}
int k1 = tp[l]+a[l];
if(0 <= k1 && k1 < 10)
{
tp[l+1] = k1;
dfs(l+1,r,a,tp);
}
int k2 = tp[l]-a[l];
if(0 <= k2 && k2 < 10 && k1 != k2)
{
tp[l+1] = k2;
dfs(l+1,r,a,tp);
}
}
void fun(int hi,int s)
{
int a[20] = {0}, tp[20] ={0};
getarr(s,a);
for(int i = 0;i < 10;++i)<span style="white-space:pre"> </span>//枚举最后一位来推前面的每一位的数
{
tp[0] = i;
dfs(0,hi,a,tp);
}
}
void solve()
{
a.push_back(7);
for(int i = 2;i < 10;++i)<span style="white-space:pre"> </span>//枚举位数
{
v.clear();
for(int j = 0;j < a.size();++j)<span style="white-space:pre"> </span>//枚举已经得到的数
{
fun(i,a[j]);
}
a.insert(a.end(),v.begin(),v.end());
sort(a.begin(),a.end());
a.erase(unique(a.begin(),a.end()),a.end());
}
}
int main()
{
//freopen("1.txt","w",stdout);
solve();
int x, y;
/*
for(int i = 0;i < a.size();++i)
cout<<a[i]<<endl;
*/
while (scanf("%d%d", &x, &y) != EOF) {
printf("%d\n", upper_bound(a.begin(), a.end(), y) - lower_bound(a.begin(), a.end(), x));
}
return 0;
}