C

来源:互联网 发布:波利亚计数定理 知乎 编辑:程序博客网 时间:2024/06/05 20:32

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
323187
Sample Output
1666266666666

       满足条件的数时含有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;elsesta2 = 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;elseleft = 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;}



原创粉丝点击