HDU5676(DFS打表+二分查找)

题目:

ztr loves lucky numbers

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1217 Accepted Submission(s): 508

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
There are T(1≤n≤10e5) cases

For each cases:

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

Output
For each cases
Output the answer

Sample Input
2
4500
47

Sample Output
4747
47

Source
BestCoder Round #82 (div.2)

题意:
t个测试样例(1<=t<=10e5), 每个样例给一个(1<=n<=10e8),找出一个大于或者等于n的最小的super lucky number(位数为偶数,只能是4和7组成)。

思路:
DFS打表,生成2位到18位之间,所有长度为偶数,每个位上由4或7组成的数的所有排列。
参数传入4的个数和7的个数。可以理解为每次往待生成的数的末尾加上一个4或7,既可以加4也可以加7,只要x>0或者y>0,就有两个函数入口,那么就可以生成全排列了。

void dfs(int x, int y, long long num){
    if(x==0&&y==0){
        arr[len++] = num;
        return;
    }
    if(x>0) dfs(x-1, y, num*10+4);
    if(y>0) dfs(x, y, num*10+7);
}

生成全排序还可以用STL中的next_permutation()函数,
用法:

do{
}while(next_permutation(arr, arr+n);

但是只能是int型的数组吗?我没有查到资料。
可以搜索一下,或者参考一下这个博客http://www.cnblogs.com/kuangbin/archive/2012/03/30/2424482.html

注意的一个坑点:
long long的范围是:2^63-1 = 9.2233720368548 * 10 18-1
要特判n>777777777444444444(7…*10e17)的情况。

代码;

#include 
#include 
#include 
//#include 
#include 
const int maxn = 500000;
typedef long long ll;
ll arr[maxn];

using namespace std;
int len=0;

void dfs(int x, int y, ll num){
    if(x==0&&y==0){
        arr[len++] = num;
        return;
    }
    if(x>0)
        dfs(x-1, y, num*10+4);
    if(y>0)
        dfs(x, y-1, num*10+7);
}

void printList(){
    for(int i=2; i<=18; i++)
        dfs(i/2, i/2, 0);
}

int main(){
    int t;
    ll n;
    printList();
    sort(arr, arr+len);
    cin>>t;
    while(t--){
        cin>>n;
        if(n>777777777444444444){
            cout<<"44444444447777777777"<continue;
        } 
        else{
            int low = 0;
            int high = len-1;
            while(low<=high){
                int mid = (low+high)/2;
                if(arr[mid]>=n)
                    high = mid-1;
                else
                    low = mid+1;
            }
            cout<return 0;
}

你可能感兴趣的:(二分/三分/尺取法)