Codeforces 96B Lucky Numbers (easy) 题解

题目链接

Codeforces 96B Lucky Numbers (easy)

思路分析

首先我们发现超级幸运数是在幸运数的基础上加了一个条件,所以不好从一个超级幸运数衍生出其它超级幸运数。但对于幸运数,只需在其后面拼上 47,即可构成一个新的幸运数。

所以我们只需广搜出所有幸运数,判断其是否大于等于 \(n\) 且为超级幸运数,找到一个最小的即可。注意最小的符合要求的超级幸运数位数不会超过 \(n\) 的位数再加 \(2\),即当 \(n\) 的位数为偶数,且与 \(n\) 同位数的超级幸运数都小于 \(n\) 时,由于超级幸运数只由 47 两种数位拼成,且个数相同,所以不可能为奇数位。此时最小的符合要求的超级幸运数位数即为 \(n\) 的位数加 \(2\)

代码呈现

to_string() 可以传入一个 short/int/long/long long 的变量并返回其对应的 string 变量。如 to_string(123) 会返回一个字符串为 123

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

const int N=10;
int n,m;

inline bool check(ll x){ // 判断是否为超级幸运数
    string s=to_string(x);
    int s1=0,s2=0;
    for (auto i:s){
        if (i=='4') ++s1;
        else ++s2;
    }
    return s1==s2;
}
ll bfs(){
    queue<ll> q;
    q.push(4),q.push(7);
    ll ans=LLONG_MAX; // 十年 OI 一场空
    while (!q.empty()){
        ll u=q.front(); q.pop();
        if (u>=n && check(u)) ans=min(ans,u);
        if (to_string(u).size()<=m+1) q.push(u*10+4),q.push(u*10+7);
    }
    return ans;
}
int main(){
    scanf("%d",&n);
    m=to_string(n).size(); // n 的位数
    printf("%lld",bfs());
    return 0;
}
posted @ 2026-01-25 17:13  CodingJuRuo  阅读(4)  评论(0)    收藏  举报