HDU 5676 ztr loves lucky numbers

代码粘上,有时间再来解释。

#include 
#include 
#include 

using namespace std;

int T;
unsigned long long int N;
int cnt;
unsigned long long int All[5050000];

unsigned long long int Ans;

bool test(unsigned long long int n)
{
    while (n)
    {
        if (n % 10ULL != 7ULL && n % 10ULL != 4ULL)
            return false;
        n /= 10ULL;
    }
    return true;
}

void dfs(const unsigned long long int &n, const int &cnt1, const int &cnt2)
{
    if (cnt1 + cnt2 > 22)
        return;
    if (cnt1 == cnt2 && cnt1 && test(n))
        All[++cnt] = n;
    dfs((n * 10ULL) + 4ULL, cnt1 + 1, cnt2);
    dfs((n * 10ULL) + 7ULL, cnt1, cnt2 + 1);
}

unsigned long long int search(const unsigned long long int &key)
{
    int l(1), r(cnt + 1), mid;
    while (l < r)
    {
        mid = l + ((r - l) >> 1);
        if (All[mid] >= key)
            r = mid;
        else
            l = mid + 1;
    }
    return All[l];
}

int main()
{
    dfs(0ULL, 0, 0);
    sort(All + 1, All + 1 + cnt);
    scanf("%d", &T);
    while (T--)
    {
        scanf("%llu", &N);
        Ans = search(N);
        if (Ans >= N)
            printf("%llu\n", Ans);
        else
        {
            for (int i = 0;i != 10;++i)
                printf("4");
            for (int i = 0;i != 10;++i)
                printf("7");
            printf("\n");
        }
    }
    return 0;
}

你可能感兴趣的:(HDU,搜索)