ztr loves lucky numbers



Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)




Problem Description


ztr 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 ztr came across a positive integer n. Help him to find the least super lucky number which is not less than n.


 



Input


(1≤n≤105) cases

For each cases:

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


 



Output


For each cases
Output the answer


 



Sample Input


2 4500 47


 



Sample Output


4747 47



解题思路:其实是一道比较简单的题目,用dfs搜一发即可。自己的代码写的好搓,参考了别人的代码。


#include<cstdio>
#include<cstring>
using namespace std;

char s[50];
bool found;
int four,seven,len;

void write(int len)
{
    for(int i = 0; i < len/2; i++) printf("4");
    for(int i = 0; i < len/2; i++) printf("7");
    printf("\n");
}
void dfs(long long ans, long long res, int lens)
{
    if(lens == len && !found){
        found = true;
        printf("%I64d\n", ans);
    }
    if(found) return;
    res = res * 10 + s[lens] - '0';
    if(res <= ans * 10 + 4 && four < len / 2){
        four++;
        dfs(ans * 10 + 4, res, lens + 1);
        four--;
        res /= 10;
    }
    if(found) return;
    if(res <= ans * 10 + 7 && seven < len / 2){
        seven++;
        dfs(ans * 10 + 7, res, lens + 1);
        seven--;
        res /= 10;
    }
}
int main()
{
    int T;scanf("%d", &T);
    while(T--){
        scanf("%s", s);
        len = strlen(s);
        if(len & 1) write(len + 1);
        else{
            four = seven = 0;
            found = false;
            dfs(0, 0, 0);
            if(!found) write(len + 2);
        }
    }
    return 0;
}