Ural binary lexicographic sequence (DP + DFS)

Source: Internet
Author: User

Http://acm.timus.ru/problem.aspx? Space = 1 & num = 1081


It is legal to have a binary sequence defined as not having two consecutive 1 occurrences. Given the length N of the sequence, find out what the K sequence is after the valid binary sequence is ordered by lexicographically.


Set DP [I] [0] and DP [I] [1] to indicate the numbers 0 and 1 on the I-th, respectively.

Then DP [I] [0] = DP [I-1] [0] + dp [I-1] [1]; DP [I] [1] = DP [I-1] [0], the table is found to be similar to the Fibonacci series.

When the k-th legal sequence is obtained, it can be found that when k> = DP [n-1], this bit is 1; otherwise, this bit is 0.


#include <stdio.h>#include <iostream>#include <map>#include <set>#include <list>#include <stack>#include <vector>#include <math.h>#include <string.h>#include <queue>#include <string>#include <stdlib.h>#include <algorithm>#define LL __int64#define eps 1e-12#define PI acos(-1.0)using namespace std;const int INF = 0x3f3f3f3f;const int maxn = 4010;int dp[50][2],tmp[50];void init(){memset(dp,0,sizeof(dp));dp[1][0] = dp[1][1] = 1;tmp[1] = 2;for(int i = 2; i < 44; i++){dp[i][0] += (dp[i-1][0] + dp[i-1][1]);dp[i][1] += dp[i-1][0];tmp[i] = dp[i][0] + dp[i][1];}}void dfs(int n, int k){if(n == 1){if(k == 1)printf("0");elseprintf("1");return;}if(k <= tmp[n-1]){printf("0");dfs(n-1,k);}else{printf("1");dfs(n-1,k-tmp[n-1]);}}int main(){init();int n,k;while(~scanf("%d %d",&n,&k)){if(k > tmp[n]){printf("-1\n");continue;}dfs(n,k);printf("\n");}return 0;}


Ural binary lexicographic sequence (DP + DFS)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.