NC15291 幸运数字Ⅱ

题目链接

题目

题目描述

定义一个数字为幸运数字当且仅当它的所有数位都是4或者7。
比如说,47、744、4都是幸运数字而5、17、467都不是。
定义next(x)为大于等于x的第一个幸运数字。给定l,r,请求出next(l) + next(l + 1) + ... + next(r - 1) + next(r)。

输入描述

两个整数l和r (1 <= l <= r <= 1000,000,000)。

输出描述

一个数字表示答案。

示例1

输入

2 7

输出

33

示例2

输入

7 7

输出

7

题解

知识点:BFS,枚举。

显然对每个数进行枚举是不可行的。而因为一大块数对应一个幸运数字,所以考虑枚举幸运数字,再遍历快速遍历目标区间。

考虑用bfs打表,因为bfs生成的数字天然排好序了。

时间复杂度 O(rl)

空间复杂度 O(?)

代码

#include <bits/stdc++.h>
#define ll long long
using namespace std;
vector<ll> a;
void bfs() {
queue<ll> q;
q.push(0);
while (!q.empty()) {
ll x = q.front();
q.pop();
if (x / (1e9) >= 1)continue;
a.push_back(x * 10 + 4);
a.push_back(x * 10 + 7);
q.push(x * 10 + 4);
q.push(x * 10 + 7);
}
}
int main() {
std::ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
bfs();
int l, r;
cin >> l >> r;
ll ans = 0;
int i = 0, pos = l;
while (a[i] < pos) i++;
while (a[i] <= r) {
ans += (a[i] - pos + 1) * a[i];
pos = a[i] + 1;
i++;
}
ans += (r - pos + 1) * a[i];
cout << ans << '\n';
return 0;
}
posted @   空白菌  阅读(36)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示