1. 程式人生 > >Codeforces Beta Round #77 (Div. 2 Only)B. Lucky Numbers (easy)

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;}