题目:
定义一个数字为幸运数字当且仅当它的所有数位都是4或者7。
比如说,47、744、4都是幸运数字而5、17、467都不是。
定义next(x)为大于等于x的第一个幸运数字。给定l,r,请求出next(l) + next(l + 1) + ... + next(r - 1) + next(r)。
#include <iostream>
#include <cmath>
#include <cctype>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <vector>
#include <queue>
#include <map>
//#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
const int MAXN = 10005;
typedef long long LL;
const LL mod = 998244353;
const LL inf = 0x3f3f3f3f;
LL a[MAXN];
int cnt;
void dfs(LL cur)
{
if(cur>=5000000000)
return ;
dfs(cur*10+4);
dfs(cur*10+7);
a[++cnt]=cur;
return ;
}
void init()
{
cnt=0;
dfs(0);
}
int main()
{
LL l,r;
init();
scanf("%lld %lld", &l, &r);
sort(a,a+cnt);
a[cnt]=0;
LL sum=0;
for(LL i=l;i<=r;)
{
LL x=lower_bound(a,a+cnt,i)-a;
//printf("%lld %lld %lld\n", i, a[x], sum);
sum+=(min(a[x],r)-i+1)*a[x];
i=a[x]+1;
}
printf("%lld\n", sum);
return 0;
}
开辟一个数组把所有符合条件的数字都存入。降低算法复杂度。
lower_bound()函数需要加载头文件#include<algorithm>,其基本用途是查找有序区间中第一个大于或等于某给定值的元素的位置,其中排序规则可以通过二元关系来表示。
int k;
k=lower_bound(a.begin(),a.end(),l)-a.begin();
LL x=lower_bound(a,a+cnt,i)-a;