【POJ】3208Apocalypse Someday-数位dp+二分

Time Limit: 1000MS   Memory Limit: 131072K
Total Submissions: 2198   Accepted: 1107

Description

The number 666 is considered to be the occult “number of the beast” and is a well used number in all major apocalypse themed blockbuster movies. However the number 666 can’t always be used in the script so numbers such as 1666 are used instead. Let us call the numbers containing at least three contiguous sixes beastly numbers. The first few beastly numbers are 666, 1666, 2666, 3666, 4666, 5666…

Given a 1-based index n, your program should return the nth beastly number.

Input

The first line contains the number of test cases T (T ≤ 1,000).

Each of the following T lines contains an integer n (1 ≤ n ≤ 50,000,000) as a test case.

Output

For each test case, your program should output the nth beastly number.

Sample Input

3
2
3
187

Sample Output

1666
2666
66666

Source

POJ Monthly--2007.03.04, Ikki, adapted from TCHS SRM 2 ApocalypseSomeday

题目大意:给定n,输出第n大包含666的数字。

思路:基本的数位dp先求解出各个数值中的有多少个含有666的,然后二分求解答案

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define maxn 22
#define ll long long
using namespace std;
ll a[maxn],dp[maxn][maxn],n;

ll dfs(ll pos,ll pre,bool limit)
{
    if(pos==-1) return pre==3;
    if(!limit&&dp[pos][pre]!=-1)
        return dp[pos][pre];
    ll ans=0,nextp,up;
    up=limit?a[pos]:9;

    for(int i=0;i<=up;i++)
    {
        if(pre==3) nextp=3;
        else if(pre==2&&i==6) nextp=3;
        else if(pre==1&&i==6) nextp=2;
        else if(pre==0&&i==6) nextp=1;
        else nextp=0;

        ans+=dfs(pos-1,nextp,limit&&(i==up));
    }
    if(!limit) dp[pos][pre]=ans;
    return ans;

}

ll calc(ll x){
    memset(dp,-1,sizeof(dp));
    ll pos = 0;
    while(x){
        a[pos ++] = x%10;
        x /= 10;
    }
    return dfs(pos - 1, 0 ,1);
}

int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        cin>>n;
        ll l = 666LL,mid;
        ll r = 100000000000LL;
        while(l < r){
            mid = (l + r)/2;
            ll temp = calc(mid);
            if(temp >= n) r = mid;
            else l = mid + 1;
        }
        cout<<l<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/wentong_Xu/article/details/82669381