C - 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.

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

       满足条件的数时含有666的,这题不一样在不是问区间【l,r】内有多少个满足的数了,而是问的第n个满足条件的数是多少。想法是,先按原来套路写出来求0—x之间有nx满足的数,然后定下来个l,r;二分逼近n求第n个数是多少。两部分都很好写,但是加一块挺不好想的。本来以为自己的二分又会输出l、mid、r傻傻分不清,结果用了个最笨的方法判断,这个可是连做二分专题的时候我都没想到的好办法。除了好几次错,二分的r太难取了,加了好几个0才到得范围。

代码如下:

#include<iostream>
#include<cstring>
using namespace std;
typedef long long LL;
int bit[30];
LL dp[30][4];
LL dfs(int pos, int sta, bool pre, bool limit)
{
	if (pos == -1)
	{
		if (sta == 3)
			return 1;
		return 0;
	}
	if (!limit && dp[pos][sta] != -1)
	{
		return dp[pos][sta];
	}
	int up = limit ? bit[pos] : 9;
	LL temp = 0;
	
	for (int i = 0; i <= up; i++)
	{
		int sta2 = 0;
		bool pre2 = 0;
		if (i != 6)
		{
			pre2 = 0;
			sta2 = sta >= 3 ? 3 : 0;
		}
		else if (i == 6)
		{
			pre2 = 1;
			if (sta == 0)
				sta2 = 1;
			if (sta == 1 || sta == 2)
			{
				if (pre)
					sta2 = sta+1;
				else
					sta2 = sta;
			}
			if (sta >= 3)
			{
				sta2 = sta;
			}
		}
		temp += dfs(pos - 1, sta2, pre2, limit && i == bit[pos]);
	}
	if (!limit)
		dp[pos][sta] = temp;
	return temp;
}
LL solve(LL x)
{
	memset(dp, -1, sizeof(dp));
	int pos = 0;
	while (x)
	{
		bit[pos++] = x % 10;
		x /= 10;
	}
	return dfs(pos - 1, 0, 0, 1);
}
void getAnswer(LL n)
{
	LL left = 0, right = 3000000000;//这个到底多大不确定,后来随便加0,好几遍才对
	LL mid;
	while (left < right)
	{
		mid = (left + right) / 2;
		//cout << left << "\t" << right << "\t" << mid << endl;
		if (solve(mid) >= n)
			right = mid;
		else
			left = mid + 1;
	}
	if (solve(left) == n)
		cout << left << endl;
	else if (solve(mid) == n)
		cout << mid << endl;
	else if (solve(right) == n)
		cout << right << endl;
}
int main()
{
	int t;
	LL n;
	cin >> t;
	while (t--)
	{
		cin >> n;
		//cout << solve(n) << endl;
		getAnswer(n);
	}
	return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值