牛客网 牛客练习赛13 B.幸运数字Ⅱ-数组 or DFS

 

B.幸运数字Ⅱ
 
 
这个题就是找出来数据范围内的所有的幸运数,然后直接区间累加起来就可以了。
两个版本,一个数组找的所有的幸运数,一个dfs找的所有的幸运数。
 
代码1(数组):
 1 //B-数组版
 2 #include<iostream>
 3 #include<cstring>
 4 #include<cstdio>
 5 #include<cmath>
 6 #include<cstdlib>
 7 #include<algorithm>
 8 #include<queue>
 9 using namespace std;
10 typedef long long ll;
11 const int maxn=2048;
12 const int inf=1e9+10;
13 ll a[maxn];
14 ll kuaisumi(int a,int b){
15     ll ans=1;
16     while(b){
17         if(b%2==1)ans=ans*a;
18         a=a*a;
19         b=b/2;
20     }
21     return ans;
22 }
23 void fun(){
24     a[1]=4,a[2]=7;ll h=2;
25     for(ll i=2;i<=10;i++){
26         ll x=kuaisumi(2,i);
27         ll y=x/2;
28         ll z=kuaisumi(10,i-1);
29         ll k=h+1;
30         for(ll j=h-y+1;j<=h;j++){
31             a[k]=4*z+a[j];
32             a[x/2+k++]=7*z+a[j];
33         }
34         h+=x;
35     }
36 }
37 int main(){
38     fun();
39     int l,r;
40     cin>>l>>r;
41     ll ans=0;
42     for(int i=1;i<=2046;i++){
43         if(a[i]>=l){
44             if(a[i]<r){
45                 ans+=(a[i]-l+1)*a[i];
46                 l=a[i]+1;
47             }
48             else{
49                 ans+=(r-l+1)*a[i];
50                 break;
51             }
52         }
53     }
54     cout<<ans<<endl;
55 }

 

代码2(DFS):

 1 //B-DFS版
 2 #include<iostream>
 3 #include<cstring>
 4 #include<cstdio>
 5 #include<cmath>
 6 #include<cstdlib>
 7 #include<algorithm>
 8 #include<queue>
 9 using namespace std;
10 typedef long long ll;
11 const int maxn=2048;
12 ll a[maxn];
13 int h=0;
14 void dfs(ll x,int c){
15     a[h++]=x;
16     if(c==9)return;
17     dfs(x*10+4,c+1);
18     dfs(x*10+7,c+1);
19 }
20 int main(){
21     a[h++]=4444444444;
22     dfs(0,0);
23     sort(a,a+h);
24     int l,r;
25     cin>>l>>r;
26     ll ans=0;
27     for(int i=0;i<h;i++){
28         if(a[i]>=l){
29             if(a[i]<r){
30                 ans+=(a[i]-l+1)*a[i];
31                 l=a[i]+1;
32             }
33             else{
34                 ans+=(r-l+1)*a[i];
35                 break;
36             }
37         }
38     }
39     cout<<ans<<endl;
40 }

 

 

 

 

 

 

 

posted @ 2018-03-19 19:50  ZERO-  阅读(237)  评论(0编辑  收藏  举报