URAL1081 Binary Lexicographic Sequence(递归)

URAL 1081. Binary Lexicographic Sequence

Time limit: 0.5 second
Memory limit: 64 MB

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 < 109) 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 output
3 1 000

Problem Author: Emil Kelevedzhiev
Problem Source: Winter Mathematical Festival Varna '2001 Informatics Tournament

题解

题意

考虑长度为N的数字串,仅仅包含01,且1不能相邻。按照字典序增序求出第K个数字串是什么?如果不存在第K个,输出 -1

思路

首先先求出fib数组来保存对于长度为从1-N的数字串的个数。观察字典序增序的数组情况可以发现规律,当前位置i为1的条件是其K值大于fib[i]的值,所以我们可以每次判断是否大于fib[i]的值来确定当前位置为0还是为1。

代码

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int INF = 0x3f3f3f3f;


const int MAXN = 44+5;
int fib[MAXN];
void init()
{
	fib[0]=1;
	fib[1]=2;
	for (int i=2;i<MAXN;i++)
		fib[i] =fib[i-1]+fib[i-2];
}

int ans[MAXN];

int main(){
	int N,K;
	init();
	while(~scanf("%d %d",&N,&K)){
		memset(ans,0,sizeof(ans));
		if(fib[N]<K){
			printf("-1\n");
		}else{
			int las = K;
			for (int j=N-1; j>= 0; j--)
		 		if (fib[j]<las){
					ans[j] =1;  
					las =las -fib[j];
				}
			for(int j=N-1;j>=0;j--){
				if(j!=0)	printf("%d",ans[j]);
				else	printf("%d\n",ans[j]);
			}
		}
	}
	return 0;
}
posted @ 2018-08-02 16:30  caomp  阅读(97)  评论(0)    收藏  举报