Apocalypse Someday(POJ-3208)
Problem 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
題意:t 組詢問,每組輸出第 n 個包含連續 的三個 6 的數
思路:數位dp,用 dp[i][0]、dp[i][1]、dp[i][2]、dp[i][3] 分別表示 i 位數中首位不含 666、首位 1個 6 且不含 666、首位連續 2 個6 且不含 666、含有 666 的數的數量,用二分不斷劃分區間找第 n 個滿足條件的數即可,由于數據范圍,二分的右邊界需要設一極大值,一般的 0x3f3f3f3f 仍達不到上界,需要換成 0x3f3f3f3f3f3f3f3f
Source Program
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<string> #include<cstdlib> #include<queue> #include<set> #include<map> #include<stack> #include<ctime> #include<vector> #define INF 0x3f3f3f3f3f3f3f3fll #define PI acos(-1.0) #define N 31 #define MOD 10007 #define E 1e-6 typedef long long LL; using namespace std; int bit[N]; LL dp[N][4]; int judge(int sta,int x) {if(sta==3)return 3;if(x!=6)return 0;return sta+1; } LL dfs(int pos,int sta,bool limit) {if(pos<0)return sta==3;if(!limit && dp[pos][sta]!=-1)return dp[pos][sta];LL temp=0;int up=limit?bit[pos]:9;for(int i=0;i<=up;i++)temp+=dfs(pos-1,judge(sta,i),limit&&i==up);if(!limit)dp[pos][sta]=temp;return temp; } LL solve(LL x) {int pos=0;while(x){bit[pos++]=x%10;x/=10;}return dfs(pos-1,0,true); } LL Find(int x) {LL left=0,right=INF;LL res=-1;while(left<=right){LL mid=(left+right)/2;if(solve(mid)<x)left=mid+1;else{res=mid;right=mid-1;}}return res; } int main() {int t;scanf("%d",&t);memset(dp,-1,sizeof(dp));while(t--){int n;scanf("%d",&n);printf("%lld\n",Find(n));}return 0; }?
總結
以上是生活随笔為你收集整理的Apocalypse Someday(POJ-3208)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数论 —— 斐波那契数列(Fibonac
- 下一篇: Two Strings Swaps(CF