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

 

B.幸运数字Ⅱ
链接: https://www.nowcoder.com/acm/contest/70/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 }

 

 

 

 

 

 

 

转载于:https://www.cnblogs.com/ZERO-/p/9729024.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值