当前位置:   article > 正文

B. Lucky Numbers (easy)思维_petya and lucky numbers

petya and lucky numbers

B. Lucky Numbers (easy)
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
Petya loves lucky numbers. Everybody knows that positive integers are lucky if their decimal representation doesn’t contain digits other than 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.

Lucky number is super lucky if it’s decimal representation contains equal amount of digits 4 and 7. For example, numbers 47, 7744, 474477 are super lucky and 4, 744, 467 are not.

One day Petya came across a positive integer n. Help him to find the least super lucky number which is not less than n.

Input
The only line contains a positive integer n (1 ≤ n ≤ 109). This number doesn’t have leading zeroes.

Output
Output the least super lucky number that is more than or equal to n.

Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator.

Examples
input
4500
output
4747
input
47
output
47

很简单的一道题,结果搞了这么长时间,最开始是想逐位的去比较,可是发现存在该位比7。这样要重这位前面一直找,很麻烦,所以直接暴力就行了,枚举这个长度的所以超级幸运数字然后在查找就行了。

代码如下:

#include<bits/stdc++.h>

using namespace std;
string n;
set<string> st;
int M;
void dfs(int i,char ch,string ans,int c4,int c7){//遍历这个长度下的所以超级幸运数字
    ans += ch;
    if(ch == '4')   c4++;
    else    c7++;
    if(i == M-1){//这里
        st.insert(ans);
        return;
    }
    if(c4 < M/2)
        dfs(i+1,'4',ans,c4,c7);
    if(c7 < M/2)
     dfs(i+1,'7',ans,c4,c7);
    return;
}
string solve(){
    int len = n.length();
    M = len;
    if(len % 2 != 0)
        M += 1;
    string tem;
    dfs(0,'4',tem,0,0);
    dfs(0,'7',tem,0,0);
    for(set<string>::iterator it = st.begin();it != st.end();++it){
        if(*it >= n || (*it).length() > len) return *it;//字符串是比较字符位的大小,所以这里要加一个长度比较

    }
    //有可能找不到,即这个位数最大的超级幸运数字还要大,所以就直接输出长度+2的最小幸运数字
    M += 2;
    string ans = "";
    for(int i=0;i<M/2;++i)
        ans += '4';
    for(int i=0;i<M/2;++i)
        ans += '7';
    return ans;
}
int main(void){
    cin >> n;
    cout << solve() << endl;
    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/72386
推荐阅读
  

闽ICP备14008679号