Description
Consider all the sequences with length (0 < N < 44), containing only the elements 0 and 1, and no two ones are adjacent (110 is not a valid sequence of length 3, 0101 is a valid sequence of length 4). Write a program which finds the sequence, which is on K-th place (0 < K < 10 9) in the lexicographically sorted in ascending order collection of the described sequences.
Input
The first line of input contains two positive integers N and K.
Output
Write the found sequence or −1 if the number K is larger then the number of valid sequences.
Sample Input
input | output |
---|---|
3 1 |
000 |
大意:两个1不能相邻,很像那道完美串,用dp来计算长度为多少时当前为什么数的时候的个数
状态转移方程 dp[i][1] = dp[i-1][0]
dp[i][0] = dp[i-1][0] + dp[i-1][1]
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; int dp[45][2]; int main() { int n,k; dp[1][0] = dp[1][1]= 1; for(int i = 2; i <= 44; i++){ dp[i][1] = dp[i-1][0]; dp[i][0] = dp[i-1][0]+dp[i-1][1]; } while(~scanf("%d%d",&n,&k)){ if(k > dp[n][1] + dp[n][0]){ printf("-1 "); continue; } while(n){ if(dp[n][0] >= k) printf("0"); else { k -= dp[n][0]; printf("1"); } n--; } printf(" "); } return 0; }