您的位置:首页 > 产品设计 > UI/UE

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

2014-01-08 11:14 411 查看


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 nth 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: