1. 程式人生 > >B. Lucky Numbers (easy)思維

B. Lucky Numbers (easy)思維

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