B. Lucky Numbers (easy)思维

来源:互联网 发布:汽车保养软件 编辑:程序博客网 时间:2024/05/20 20:46

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;}
原创粉丝点击