【CSP - S T1】格雷碼

LinkLink

luoguluogu P5657P5657

DescriptionDescription

在這裏插入圖片描述

SampleSample InputInput 11

2 3

SampleSample OutputOutput 11

10

SampleSample InputInput 22

3 5

SampleSample OutputOutput 22

111

SampleSample InputInput 33

44 1145141919810

SampleSample OutputOutput 33

00011000111111010000001001001000000001100011

HintHint

TrainTrain ofof ThoughtThought

kk在當前個數的左邊(對於中間值而言),則當前位爲0(這一邊的上一位不是1)
kk在當前個數的右邊(同上),則當前位爲1(同上)
若上一位爲1,則將上述規律調換一遍

CodeCode

#include<iostream>
#include<cstdio>
#define ull unsigned long long 

int n;
ull k;

using namespace std;

int main()
{
	ull l, r; 
	scanf("%d", &n);
	cin >> k;
	if (n == 64) {
		return !printf("1000000000000000000000000000000000000000000000000000000000000000");//對數據的特判
	}
	 else l = 1, r = 1ull << n;
	bool pd = 0;
	while (l < r)
	{
		ull mid =(ull) (l + r) >> 1;//取中間值
		if (k < mid) {
			r = mid; 
			if (pd == 1) printf("1"), pd = 0;
			 else printf("0");//同思路(pd判斷上一位是否爲1)
		} 
		 else {
		 	l = mid + 1;
		 	if (pd == 1) printf("0");
		 	 else printf("1");//同上
		 	pd = 1;
		 } 
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章