Apocalypse Someday (数位dp+二分)

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

题目大概:

输入n,找出第n大个含有666的数字。

思路:

这个题和基本的题型找出含有47的数字的数量差不多,这个是找出含有666的数字的数量。

但是这个题不是问的数量有多少,而是问的第n大个,那个数量已经固定了,只需要算出1到某个数含有666的数量最接近n的那个数是什么,即可。

也就是用一下二分,二分所有数,找出一个数量是小于n的最大的那个就行了。


代码:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long LL;
LL  INF=0xfffffffffLL;
int a[22];
LL dp[22][2][2][2];
LL sove(int pos,int q1,int q2,int k,int limit)
{
    if(pos==-1)return k;

    if(!limit&&dp[pos][q1][q2][k]!=-1)return dp[pos][q1][q2][k];
    int end=limit?a[pos]:9;
    LL ans=0;
    for(int i=0;i<=end;i++)
    {
        if(k==1)ans+=sove(pos-1,i==6,q1,1,limit&&i==end);
        else ans+=sove(pos-1,i==6,q1,q1&&q2&&i==6,limit&&i==end);
    }
    if(!limit)dp[pos][q1][q2][k]=ans;
    return ans;
}
LL go(LL x)
{
    int pos=0;
    while(x)
    {
        a[pos++]=x%10;
        x/=10;
    }
    return sove(pos-1,0,0,0,1);
}
int main()
{   int t;
    LL n;
    memset(dp,-1,sizeof(dp));


    scanf("%d",&t);
    while(t--)
    {
        scanf("%I64d",&n);
        LL l=1,r=INF,mid;
        while(l<=r)
        {
            mid=(l+r)/2;
            if(go(mid)<n)
            {
                l=mid+1;
            }
            else
            {
                r=mid-1;
            }

        }
       printf("%I64d\n",l);

    }


    return 0;
}






  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值