UVA 10479 - The Hendrie Sequence(规律+递归)

Hendrie Sequence 

The Hendrie Sequence ``H" is a self-describing sequence defined as follows:

  • H(1) = 0
  • If we expand every number x in H to a subsequence containing x 0's followed by the number x + 1, the resulting sequence is still H (without its first element).

Thus, the first few elements of H are:


0,1,0,2,1,0,0,3,0,2,1,1,0,0,0,4,1,0,0,3,0,...


You must write a program that, given n, calculates the nth element of H.

Input 

Each test case consists of a single line containing the integer  n  (   0 < n < 263 ) . Input is terminated with a line containing the number ` 0 ' which of course should not be processed.

Output 

For each test case, output the  n th element of H on a single line.

Sample Input 

4
7
44
806856837013209088
0

Sample Output 

2
0
3
16

题意:求Hendrie序列第n项是多少。

思路:写出前几个序列为

0 1 02 1003 02110004 1003020211100005.....

发现规律,以1,2,4,8为长度分界,每个串由1个i-2串,2个i-3串,3个i-4串....最后末尾在加上i。有了这个规律便可以递归求解,n表示为当前还需要的长度,然后用2*m去找到一个不小于n的数字,如果等于,说明正好找到了,如果大于,那么从后面往前考虑,先把0和1的情况考虑完。如果还不满足,继续往前考虑长度为2以上的串,如果找到一个小于的,说明就在这个情况里面,然后剩下的长度为2 * 长度 - n。递归求解。


这题被坑得很惨啊,主要是题目n范围太大了,要用unsigned long long才能存的下,并且一开始求2次方的时候直接用log去求,结果由于n很大会有误差。看了网上别人一个代码,知道有1ULL这个东西,如果用1ULL,那么左移位数就可以为63位了。

代码:

#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;

unsigned long long n;

unsigned long long solve(unsigned long long n) {
	unsigned long long m;
	while ((1ULL<<m) < n) {m++;}
	if ((1ULL<<m) == n) return m;
	n = (1ULL<<m) - n - 1;
	if (n < m - 1) return 0;
	else n -= m - 1;
	if (n < m - 2) return 1;
	else n -= m - 2;
	for (unsigned long long k = 1; ; k++) {
		unsigned long long len = (1ULL<<k);
		for (unsigned long long i = 0; i < m - k - 2; i++) {
			if (n < len)
				return solve(2 * len - n);
			else n -= len;
		}
	}
}

int main() {
	while (cin >> n && n) {
		cout << solve(n) << endl;
	}
	return 0;
}


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值