[CQOI2016] 手机号码
题目描述
人们选择手机号码时都希望号码好记、吉利。比如号码中含有几位相邻的相同数字、不含谐音不吉利的数字等。手机运营商在发行新号码时也会考虑这些因素,从号段中选取含有某些特征的号码单独出售。为了便于前期规划,运营商希望开发一个工具来自动统计号段中满足特征的号码数量。
工具需要检测的号码特征有两个:号码中要出现至少 3 3 3 个相邻的相同数字;号码中不能同时出现 8 8 8 和 4 4 4。号码必须同时包含两个特征才满足条件。满足条件的号码例如:13000988721、23333333333、14444101000。而不满足条件的号码例如:1015400080、10010012022。
手机号码一定是 11 11 11 位数,且不含前导的 0 0 0。工具接收两个数 L L L 和 R R R,自动统计出 [ L , R ] [L,R] [L,R] 区间内所有满足条件的号码数量。 L L L 和 R R R 也是 11 11 11 位的手机号码。
输入格式
输入文件内容只有一行,为空格分隔的 2 2 2 个正整数 L , R L,R L,R。
输出格式
输出文件内容只有一行,为 1 1 1 个整数,表示满足条件的手机号数量。
样例 #1
样例输入 #1
12121284000 12121285550
样例输出 #1
5
提示
样例解释:满足条件的号码: 12121285000、 12121285111、 12121285222、 12121285333、 12121285550。
数据范围: 1 0 10 ≤ L ≤ R < 1 0 11 10^{10}\leq L\leq R<10^{11} 1010≤L≤R<1011。
原题
代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll dp[16][16][16][2][2][2]; // dp记录[pos][last][llast][exist_4][exist_8][ok]状态下对答案的贡献
int a[16]; // a[]记录数字串
// pos为此时的位置,last为上一位的数,llast为上上一位的数
// exist_4表示4是否存在,exist_8表示8是否存在,ok表示当前是否存在连续三位相同
// bound表示前面每一位是否都是上界,lead_0表示是否前面全是0
ll dfs(int pos, int last, int llast, int exist_4, int exist_8, int ok, bool bound, bool lead_0)
{
if (exist_4 && exist_8) // 同时存在4和8直接返回0
return 0;
if (pos == 0) // 枚举完每一位时返回
return ok;
if (!bound && !lead_0 && dp[pos][last][llast][exist_4][exist_8][ok] != -1) // 读取记忆(doge
return dp[pos][last][llast][exist_4][exist_8][ok];
int max_num; // 可枚举的该位的数的上界
if (bound)
max_num = a[pos];
else
max_num = 9;
ll res = 0;
for (int i = 0; i <= max_num; i++)
{
if (lead_0 && i == 0)
res += dfs(pos - 1, i, last, exist_4 || (i == 4), exist_8 || (i == 8), ok, bound && (i == a[pos]), 1);
else
res += dfs(pos - 1, i, last, exist_4 || (i == 4), exist_8 || (i == 8), ok || (last == llast && i == last), bound && (i == a[pos]), 0);
}
if (!bound && !lead_0) // 没在边界时,记录下该状态对应的答案,记忆化
dp[pos][last][llast][exist_4][exist_8][ok] = res;
return res;
}
ll solve(ll x)
{
int len = 0;
while (x)
{
a[++len] = x % 10;
x /= 10;
}
return dfs(len, -1, -1, 0, 0, 0, 1, 1);
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
memset(dp, -1, sizeof(dp)); // 将dp数组初始化为-1,表示对应状态的答案目前还未计算出
ll l, r;
cin >> l >> r;
cout << solve(r) - solve(l - 1) << '\n';
return 0;
}