首页 > 代码库 > poj 3208 Apocalypse Someday (数位dp)

poj 3208 Apocalypse Someday (数位dp)

Apocalypse Someday
Time Limit: 1000MS Memory Limit: 131072K
Total Submissions: 1490 Accepted: 686

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个包含666的数字。


思路:

考虑数位,考虑当前位置,有三种状态,0表示没有6,1表示有6,2表示有66,3表示有666。

dp[i][j]表示第i位前缀状态为j时能得到包含666数字的方案数,那么枚举当前位置选多少来进行状态转移即可。

输出方案先找到位数(与dp[i][0]比较),然后逐位确定,状态也要逐位更新。


代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <string>
#include <map>
#include <stack>
#include <vector>
#include <set>
#include <queue>
#include <sstream>
#define maxn 1005
#define MAXN 200005
#define mod 1000000007
#define INF 0x3f3f3f3f
#define pi acos(-1.0)
#define eps 1e-4
typedef long long ll;
using namespace std;

ll n,m,k,ans,tot,cnt,flag;
ll dp[15][4],tran[4][10];

void presolve() // 预处理dp
{
    ll i,j,t;
    tran[0][6]=1,tran[1][6]=2,tran[2][6]=3;
    for(i=0;i<=9;i++) tran[3][i]=3;
    dp[0][3]=1;
    for(i=1;i<=12;i++)
    {
        for(j=0;j<=3;j++)
        {
            for(k=0;k<=9;k++)
            {
                dp[i][j]+=dp[i-1][tran[j][k]];
            }
        }
    }
}
void solve()
{
    ll i,j,st;
    for(i=1;i<=12;i++)  // 找到位数
    {
        if(dp[i][0]>=n){ tot=i; break; }
    }
    st=0;
    for(i=tot;i>=1;i--) // 逐位确定
    {
        for(j=0;j<=9;j++)
        {
            if(dp[i-1][tran[st][j]]>=n)
            {
                st=tran[st][j];
                printf("%d",j);
                break ;
            }
            n-=dp[i-1][tran[st][j]];
        }
    }
    puts("");
}
int main()
{
    ll i,j,t;
    presolve();
    scanf("%lld",&t);
    while(t--)
    {
        scanf("%lld",&n);
        solve();
    }
    return 0;
}


poj 3208 Apocalypse Someday (数位dp)