Ural(Timus) 1081. Binary Lexicographic Sequence

版权声明:仅供研究,转载请注明出处。 https://blog.csdn.net/CSUstudent007/article/details/82425638

 题意:

有一串01排列的字符,长度为n,不能让两个‘1’相邻,将他们按字典序升序排列,输出第k个字符串。

也就是说000可以,001可以,101可以,011不行。

当时我看题目时没看仔细,以为两个‘0’也不能相邻,因为原文是这么说的:no two ones are adjacent.我理解成了是两个字符不能相邻。。。然后死活都想不出怎么做。。。

题解:

从高往低按位置先预处理该位置填0或1的方法数,(按字典序,左边是高位,右边是低位)。

a[1][0]=a[1][1]=1;
	for(int i=2;i<N;i++){
		a[i][0]=a[i-1][0]+a[i-1][1];
		a[i][1]=a[i-1][0];
	}

然后判断与k的关系, 如果:

1.a[n][1]+a[n][0]<k,说明k大于总排列数,输出-1.

2.按下面代码:a.高位能填0,那么就填0(也就是左边能填0就填0)b.不能填0了,也就是说明现在的序数太小,序数要上升才能到第k个,此时输出1,k-=a[n][0],如此,继续循环。

while(n){
		if(a[n][0]>=k){
			cout<<"0";
		}
		else{
			k-=a[n][0];
			cout<<"1"; 
		}
		n--;
	}

 代码:

#include<iostream>
#include<cstring>
using namespace std;
const int N = 45;
typedef long long ll;
ll a[N][2];
int main(){
	int n;
	ll k;
	cin>>n>>k;
	a[1][0]=a[1][1]=1;
	for(int i=2;i<N;i++){
		a[i][0]=a[i-1][0]+a[i-1][1];
		a[i][1]=a[i-1][0];
	}
	if(a[n][1]+a[n][0]<k){
	 	cout<<"-1"<<endl;
	 	return 0;
	 }
	else{
	while(n){
		if(a[n][0]>=k){
			cout<<"0";
		}
		else{
			k-=a[n][0];
			cout<<"1"; 
		}
		n--;
	}
	cout<<endl;
}
return 0;
}

猜你喜欢

转载自blog.csdn.net/CSUstudent007/article/details/82425638