POJ 3208 Apocalypse Someday

105 篇文章 0 订阅
30 篇文章 0 订阅

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

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

二分+数位DP~

如果我们知道一个数x,就可以用数位DP求出<x的符合要求数的个数。那么我们二分x,再求出数的个数,最后输出二分得到的x即可。

用f[i][j]表示第i位,目前状态为j时的方案数。j==0~2分别表示末尾有0~2个连续的6,且数中没有连续3个6出现过。j==3表示数中出现过连续3个6,不要求是在末尾。

那么容易给出转移方程:

f[i][0]=f[i-1][1]*9+f[i-1][2]*9+f[i-1][0]*9;

f[i][1]=f[i-1][0];

f[i][2]=f[i-1][1];

f[i][3]=f[i-1][2]+f[i-1][3]*10;

注意二分的时候求的是<x的值,所以mid要+1。有可能出现l+1==r的无限循环,所以l+1==r就跳出,单独判断。

(个人认为按位求总数最麻烦……调了好久……见代码cal()函数~)


#include<cstdio>
#define ll long long

int t,n;
ll l,r,mid,f[20][4];

int read()
{
	int x=0,f=1;char ch=getchar();
	while(ch<'0' || ch>'9') {if(ch=='-') f=-1;ch=getchar();}
	while(ch>='0' && ch<='9') {x=(x<<1)+(x<<3)+ch-'0';ch=getchar();}
	return x*f;
}

int cal(ll u)
{
	int now,wei=0,tot=0,cnt=0,cnt1;ll i,v=0;
	for(i=1;i<u;i*=10,wei++);
	while(v<u)
	{
		while(v+i<=u)
		{
			v+=i;
			if(cnt==3) cnt1=3;
			else if(v/i%10==7) cnt1=cnt+1;
			else cnt1=0;
			for(int j=3;j>=3-cnt1;j--) tot+=f[wei][j];
		}
		if(cnt!=3) cnt=v/i%10==6 ? cnt+1:0;wei--;i/=10;
	}
	return tot;
}

int main()
{
	t=read();f[0][0]=1;
	for(int i=1;i<=19;i++)
	{
	  	f[i][1]=f[i-1][0];
	  	f[i][2]=f[i-1][1];
	  	f[i][3]=f[i-1][2]+f[i-1][3]*10;
	  	f[i][0]=f[i-1][1]*9+f[i-1][2]*9+f[i-1][0]*9;
	}
	while(t--)
	{
		n=read();l=0,r=10000000000ll;
		while(l+1<r)
		{
			mid=l+r>>1;
			if(cal(mid+1)>=n) r=mid;
			else l=mid;
		}
		if(l+1==r) if(cal(r)>=n) printf("%lld\n",l);
		else printf("%lld\n",r);
	}
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值