1. 程式人生 > 實用技巧 >幸運數字(dfs+暴力)-牛客

幸運數字(dfs+暴力)-牛客

幸運數字(dfs+暴力)-牛客

題意:定義一個數字為幸運數字當且僅當它的所有數位都是4或者7。 比如說,47、744、4都是幸運數字而5、17、467都不是。

定義next(x)為大於等於x的第一個幸運數字。給定l,r,請求出next(l) + next(l + 1) + ... + next(r - 1) + next(r)。

暴力找出所有的幸運數字,存進陣列,二分查詢,分塊求和

程式碼:

#include<bits/stdc++.h>
/*#include<iostream>
#include<string>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<queue>
#include<cstring>
*/ using namespace std; const int maxn=1e6+10; const int mod=19260817; const int inf=0x3f3f3f3f; typedef long long ll; typedef pair<int,int> pii; const int N=5e5+10; ll l,r; ll ans; ll a[maxn]; int cnt=2; void dfs(ll x) { if(x>1e9) return ; if(x>10) a[cnt++]=x; dfs(x*10+4); dfs(x
*10+7); } int main() { cin>>l>>r; a[0]=4; a[1]=7; dfs(4); dfs(7); a[cnt]=44444444444;//界限 sort(a,a+cnt+1); int L=lower_bound(a,a+cnt+1,l)-a; int R=upper_bound(a,a+cnt+1,r)-a; for(int i=L; i<=R; i++) { ans+=(min(a[i],r)-l+1)*a[i];//分塊
//cout<<ans<<" "; l=a[i]+1; } cout<<ans<<endl; system("pause"); return 0; }