UVA 10479 - The Hendrie Sequence(规律+递归)
2014-01-08 11:14
411 查看
Hendrie Sequence |
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 ofH 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;
}
相关文章推荐
- uva 10479 - The Hendrie Sequence(规律+递归)
- UVA 10479 The Hendrie Sequence 规律
- uva 10479(找规律+递归)
- The Hendrie Sequence UVA - 10479
- uva 10479(找规律+递归)
- UVA11384 Help is needed for Dexter (递归、找规律)
- UVA 12627 <递归找规律,紫书p245页例题>
- UVA 10479 The Hendrie Sequence
- UVa 12627 (递归 计数 找规律) Erratic Expansion
- UVa12674 Erratic Expansion (递归+规律)
- uva 10479——The Hendrie Sequence
- UVA12627 Erratic Expansion (递归找规律)
- Optimal Array Multiplication Sequence UVA - 348 (最优矩阵链乘+递归输出路径+区间dp)
- Brackets sequence UVA - 1626 (典型的区间dp+递归打印路径)
- UVA - 12627 - Erratic Expansion(找规律递归)
- Uva Ducci Sequence(map映射的哈希表)
- 紫书章六例题四 悲剧文本 UVA 11988 (用数组模拟单向链表/递归)
- uva 348 - Optimal Array Multiplication Sequence
- UVA 11384 最少操作使数列变为零 (找规律)
- GCD XOR UVA 12716 找规律 给定一个n,找多少对(a,b)满足1<=b<=a<=n,gcd(a,b)=a^b;