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;
}