POJ3208:Apocalypse Someday

题目描述

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.

输入格式

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.

输出格式

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


翻译:给出n,问1~n中含有666的数的个数

很明显的数位动规。我们用记忆化搜索来做,先设计状态。

len,pre1,pre2表示当前为第len位,前一位是否为6,前第二位是否为6。为了减少思维复杂度,我们可以数位动规算出有多少不含666的数的个数。那么设(len,pre1,pre2)表示不含666的数的个数,可以很容易写出代码:
long long dfs(int len,bool pre1,bool pre2,bool havelim){
    if(len==0) return 1;
    if(!havelim&&dp[len][pre1][pre2]) return dp[len][pre1][pre2];
    int lim=(havelim?bit[len]:9);
    long long cnt=0;
    for(register int i=0;i<=lim;i++){
        if(pre1&&pre2&&i==6) continue;
        cnt+=dfs(len-1,(i==6),pre1,(havelim&&i==lim));
    }
    return havelim?cnt:dp[len][pre1][pre2]=cnt;
}

完整代码:

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;

long long dp[21][2][2];
int n,bit[21];

inline int read(){
    register int x(0),f(1); register char c(getchar());
    while(c<'0'||'9'<c){ if(c=='-') f=-1; c=getchar(); }
    while('0'<=c&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar();
    return x*f;
}

long long dfs(int len,bool pre1,bool pre2,bool havelim){
    if(len==0) return 1;
    if(!havelim&&dp[len][pre1][pre2]) return dp[len][pre1][pre2];
    int lim=(havelim?bit[len]:9);
    long long cnt=0;
    for(register int i=0;i<=lim;i++){
        if(pre1&&pre2&&i==6) continue;
        cnt+=dfs(len-1,(i==6),pre1,(havelim&&i==lim));
    }
    return havelim?cnt:dp[len][pre1][pre2]=cnt;
}

inline bool check(long long x){
    int d=0; long long tmp=x;
    while(x) bit[++d]=x%10,x/=10;
    return (tmp+1-dfs(d,false,false,true))>=n;
}

int main(){
    int t=read();
    while(t--){
        n=read();
        long long l=0,r=1e18,mid=0,ans=0;
        while(l<=r){
            mid=l+r>>1;
            if(check(mid)) ans=mid,r=mid-1;
            else l=mid+1;
        }
        printf("%lld\n",ans);
    }
    return 0;
}

转载于:https://www.cnblogs.com/akura/p/10908146.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值