Codeforces Beta Round #77 (Div. 2 Only)B. Lucky Numbers (easy)

题意

寻找一个最小的 大于n的super lucky数字,super lucky数字时只含4和7。

 思路

最初想着拼凑,找规律,没办法只有DFS了,

INF设的太小wa,ans会超int

ans的临时变量tem忘开long long又wa

AC Code

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF = 1e13+5;
ll minl(int n) {
	int len = n/2,len2 = n/2;
	ll ans = 0;
	while(len--) {
		ans*=10;
		ans+=4;
	}
	while(len2--) {
		ans*=10;
		ans+=7;
	}
	return ans;
}
ll maxl(int n) {
	int len = n/2, len2 = n/2;
	ll ans = 0;
	while(len--) {
		ans*=10;
		ans+=7;
	}
	while(len2--) {
		ans*=10;
		ans+=4;
	}
	return ans;
}
ll cnt,ans,n;
bool check(ll n) {
	int d[15],cnt = 0;
	while(n) {
		d[cnt++] = n%10;
		n/=10;
		if(d[cnt-1] != 4 && d[cnt-1] != 7) return 0;
	}
	int x=0,y=0;
	for(int i = 0; i<cnt; i++) {
		if(d[i] == 4) x++;
		else if(d[i] == 7) y++;
	}
	if(x == y) {
		return 1;
	}
	return 0;
}
void dfs(int step,ll sum) {
	if(step == cnt && sum >= n && check(sum)) {
		ans = min(sum,ans);
	}
	if(step == cnt) return ;
	sum *=10;
	step++;
	ll tem=sum+4,tem1=sum+7;
	dfs(step,tem);
	dfs(step,tem1);
}
int main() {
	ans = INF;
	cin>>n;
	cnt = 0;
	int d[15],dd = 1;
	int tem = n;
	while(tem) {
		cnt++;
		d[dd++] = tem%10;
		tem/=10;
	}

	if(cnt%2 || n>maxl(cnt)) cout<<minl(cnt+2)<<endl;
	else {
		//if(cnt>=10) cout<<"4444477777"<<endl;
		//else {
			dfs(0,0);
			cout<<ans<<endl;
	//	}
	}
	return 0;
}

正宗递归

#include<iostream>
using namespace std;
long long n, ans = 1LL << 60;
void F(long long x, int y, int z) {//通过x构造答案,y是4的个数,z是7点个数 
	if(x >= n && y == z) ans=min(ans, x);//答案ans满足要求:1.大于等于n  2.只存在7和4,且7的个数等于4的个数
	if(x > n * 100) return;//答案肯定在n和n*100之间,所以x>n*100的时候退出; 
	F(x * 10 + 4, y + 1, z);//当前答案x加一位数4 
	F(x * 10 + 7, y, z + 1);//当前答案x加一位数7
}
int main() {
	cin >> n;
	F(0, 0, 0);
	cout << ans;
	return 0;}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值