Apocalypse Someday
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。
百度,发现网上的做法几乎都是自动机dp???
然而并不会什么自动机dp,于是写完二分+dp交上去一看,速度垫底,代码长度倒数……
而且还调错调得心累…..(╯‵□′)╯︵┻━┻
思路:
首先考虑二分答案,那么就变成了判断小于一个数的”beastly number”有多少个。
考虑设
f[i][j(0≤j≤3)][0/1]
表示状态:
i
代表当前进行到了第
j
分别表示从当前位开始的后缀上有
最后一维的
0/1
代表是否触碰边界。
然后可以发现这就是个数位dp,直接做就好了~
细节较多,实现时需仔细考虑。
然后显然上面这两句话才是本题的精髓
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
using namespace std;
typedef long long ll;
inline ll read()
{
ll x=0;char ch=getchar();
while(ch<'0' || '9'<ch)ch=getchar();
while('0'<=ch && ch<='9')x=x*10+(ch^48),ch=getchar();
return x;
}
bool flag;
ll n;
ll f[12][4][3],s[12];
char st[12];
inline ll judge(ll x)
{
sprintf(st+1,"%lld",x);
int m=strlen(st+1);
reverse(st+1,st+m+1);
for(int i=1;i<=m;i++)
s[i]=st[i]-'0';
memset(f,0,sizeof(f));
if(s[m]==6)
{
f[m][1][1]=1;
f[m][0][0]=6;
}
else
{
f[m][0][1]=1;
f[m][0][0]=s[m];
if(6<s[m])
{
f[m][1][0]=1;
f[m][0][0]--;
}
}
for(int i=m-1,ty;i>=1;i--)
{
if(s[i]==6)ty=1;
else ty=0;
for(int j=0;j<=2;j++)
{
f[i][0][0]+=f[i+1][j][0]*9ll;
if(6>=s[i])
f[i][0][0]+=f[i+1][j][1]*s[i];
else
f[i][0][0]+=f[i+1][j][1]*(s[i]-1);
if(s[i]!=6)f[i][0][1]+=f[i+1][j][1];
}
f[i][1][0]=f[i+1][0][0];
f[i][2][0]=f[i+1][1][0];
if(s[i]>=6)
{
f[i][1][ty]+=f[i+1][0][1];
f[i][2][ty]+=f[i+1][1][1];
}
f[i][3][0]=f[i+1][2][0]+f[i+1][3][0]*10;
f[i][3][0]+=f[i+1][3][1]*s[i];
f[i][3][1]+=f[i+1][3][1];
if(s[i]>=6)
f[i][3][ty]+=f[i+1][2][1];
}
return f[1][3][0]+f[1][3][1];
}
void mian()
{
n=read();
ll l=666,r=6668056399,mid,ans=666;
while(l<=r)
{
mid=l+r>>1;
if(judge(mid)>=n)
ans=mid,r=mid-1;
else
l=mid+1;
}
printf("%lld\n",ans);
}
int main()
{
int T=read();
while(T--)
mian();
return 0;
}