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.
计数类dp的变种。
先预处理出dp[i][0..3],0..2表示i位数里开头有0..2个6的【非魔鬼数数量】,3表示i位数里的魔鬼数数量。
然后从高位向低位试填。在每一位数字从小到大试填。如果填上这个数总数就多了,那这一位就填这个数【但是不累加进总数】,否则将总数累加,并试填下一个数。
如何计算填好该位后的总数呢?不妨设i位填j之后,结尾6的个数为cnt。【这里注意,和前面的dp数组定义时一样,cnt=3代表是魔鬼数(即前面已经出现了666),并不一定结尾要有666,同理cnt<3代表结尾有cnt个6,且不是魔鬼数。例如5666066___的cnt是3】那么后面可以填dp数组下标为3,2,…,3-cnt的数。
即tot=now+∑(dp[i-1][j]|cnt+j>=3)。now表示之前的总数。
#include<cstdio>
#include<cstring>
int dp[20][5],ans[20];
int main()
{
int i,j,k,m,n,p,q,x,y,z,T,now,cnt,tot;
dp[0][0]=1;
for (i=0;i<=15;i++)
for (j=0;j<=3;j++)
{
dp[i+1][j==3?3:j+1]+=dp[i][j];
dp[i+1][j==3?3:0]+=dp[i][j]*9;
}
scanf("%d",&T);
while (T--)
{
memset(ans,0,sizeof(ans));
scanf("%d",&x);
p=3;
while (dp[p][3]<x) p++;
now=cnt=0;
for (i=p;i>=1;i--)
{
for (j=0;j<=9;j++)
{
y=cnt;
if (cnt<3)
{
if (j==6) cnt++;
else cnt=0;
}
tot=now;
for (k=3;k>=0;k--)
if (cnt+k>=3) tot+=dp[i-1][k];
if (tot>=x)
{
ans[i]=j;
break;
}
now=tot;
cnt=y;
}
}
for (i=p;i>=1;i--)
printf("%d",ans[i]);
printf("\n");
}
}