1. 程式人生 > >poj 3208 Apocalypse Someday 數位dp+二分答案

poj 3208 Apocalypse Someday 數位dp+二分答案

Apocalypse Someday

Time Limit: 1000MS Memory Limit: 131072K
Total Submissions: 2203 Accepted: 1110

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 n

th 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

題意:

求第nn小的數位中含有三個連續的6的數。

簡單數位DP+二分

#include<iostream>
#include<cstdio>
#include<cstring>

using namespace std;
typedef long long ll;
ll dp[30][30];
int a[30];
ll dfs(int pos,int sta,bool limit)
//計算
{
	if(pos==-1){
		return sta==3;
	}
	if(!limit&&dp[pos][sta]!=-1) 
	return dp[pos][sta];
	int up=limit?a[pos]:9;
	ll tmp=0;
	for(int i=0;i<=up;i++)
	{
	 if(sta==3)
	 tmp+=dfs(pos-1,sta,limit&&i==up);
	 else if(i==6)
	 tmp+=dfs(pos-1,sta+1,limit&&i==up);
	 else
	 tmp+=dfs(pos-1,0,limit&&i==up);
	}
	if(!limit) 
	dp[pos][sta]=tmp;
	return tmp; 
}
 
ll solve(ll x)
{
	ll t=x;
    int pos=0;
    while(x)
    {
        a[pos++]=x%10;
        x/=10;
    }
    return dfs(pos-1,0,true);
    
}
int main()
{
	
    memset(dp,-1,sizeof(dp));
    int T;
    cin>>T;
    for(int i=1;i<=T;i++)
    {
	ll n,m;
	scanf("%lld",&n);
	ll l=666,r=1e18,mid;
	while(l<=r)
	{
	
	 mid=(l+r)/2;
	 if(solve(mid)>=n)
	 	r=mid-1;
	 else
	 	l=mid+1;
	 	
	}
	printf("%lld\n",l);
    }

    return 0;
}