POJ-3028:Apocalypse Someday(数位DP)

Apocalypse Someday
Time Limit: 1000MS Memory Limit: 131072K
Total Submissions: 2112 Accepted: 1049
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

思路:二分枚举。用数位DP判断上下界。

#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
typedef long long ll;
int p[40];
ll d[40][10][4];//d[i][j][k]表示在第i位的数为j,且有连续k个6的数的个数
ll f[20];
ll check(ll x)
{
    int n=0;
    ll y=x;
    while(x)p[n++]=x%10,x/=10;n--;
    memset(d,0,sizeof d);
    for(int i=0;i<=n;i++)
    {
        if(i==0)
        {
            for(int j=0;j<=5;j++)d[i][j][0]=1;
            for(int j=7;j<=9;j++)d[i][j][0]=1;
            d[i][6][1]=1;
            continue;
        }
        for(int j=0;j<=9;j++)
        {
            for(int k=0;k<=9;k++)
            {
                d[i][j][3]+=d[i-1][k][3];
                if(j==6)
                {
                    d[i][j][1]+=d[i-1][k][0];
                    d[i][j][2]+=d[i-1][k][1];
                    d[i][j][3]+=d[i-1][k][2];
                }
                else d[i][j][0]+=d[i-1][k][0]+d[i-1][k][1]+d[i-1][k][2];
            }
        }
    }
    ll ans=0;
    for(int i=0;i<n;i++)
    {
        for(int j=1;j<=9;j++)ans+=d[i][j][3];
    }
    int now=0;
    for(int i=n;i>=0;i--)
    {
        if(i==n)
        {
            for(int j=1;j<p[i];j++)ans+=d[i][j][3];
        }
        else
        {
            if(now==3)
            {
                ans+=y;
                break;
            }
            for(int j=0;j<p[i];j++)
            {
                for(int k=3;k+now>=3;k--)ans+=d[i][j][k];
            }
        }
        if(p[i]==6)now++;
        else now=0;
        y-=p[i]*f[i];
    }
    return ans+(now>=3);
}
int main()
{

    f[0]=1;
    for(int i=1;i<=18;i++)f[i]=f[i-1]*10;
    int T;
    cin>>T;
    while(T--)
    {
        ll n;
        scanf("%lld",&n);
        ll l=1,r=n*1000+666,ans=0;
        while(r>=l)
        {
            ll m=(l+r)/2;
            if(check(m)>=n)
            {
                ans=m;
                r=m-1;
            }
            else l=m+1;
        }
        printf("%lld\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Mitsuha_/article/details/81279692