您的位置:首页 > 其它

UVA - 1350 Pinary (递推)

2014-08-22 19:41 344 查看
Description



``Pinary" number is a positive number using only two digits ``0" and ``1" with usual rule that it must not begin with a 0, and the additional rule that two successive digits must not be both ``1". This means that the factor ``11" is forbidden in the string.
So the allowed Pinary writings are 1, 10, 100, 101, 1000, 1001,..., 100010101010100010001. For example, ``100101000" is a Pinary number, but neither ``0010101" nor ``10110001" are Pinary numbers.

Each Pinary number represents a positive integer in the order they appear (using length order, lexicographic order), that is, 1 is mapped to 1, 10 is mapped to 2. And 100, 101 and 1000 are mapped to 3, 4 and 5, respectively. You are to write a program to
generate Pinary number representations for integers given.

Input

Your program is to read from standard input. The input consists of
T test cases. The number of test cases T is given in the first line of the input. Each test case starts with a line containing a postive integer2 <
K < 90, 000, 000.

Output

Your program is to write to standard output. Print exactly one line for each test case. For each test case, print the Pinary number representation for input integer. The following shows sample input and output for three test cases.

Sample Input

3 
7 
2000 
22


Sample Output

1010 
1001000001001000 
1000001
题意:把所有的不含前导0和连续1的二进制串从小到大排列,求第k个串
思路:思路和求第K大的排列UVA - 12335 Lexicographic Order (第k大排列) 是一样的,我们先统计出长度不超过i的串的个数,那么我们先推出长度为j的串的个数:
num[j] = num[j-1]+num[j-1],依次假设长为j的串的第i-2位就能推出来了,然后就是每次找第n个串能在的位置,每次确定最大的一位,依次类推
[code]#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
typedef long long ll;
using namespace std;
const int maxn = 105;

ll num[maxn], sum[maxn], ans[maxn];
ll n;

void init() {
	memset(num, 0, sizeof(num));
	memset(sum, 0, sizeof(sum));
	num[1] = num[2] = 1;
	sum[1] = 1, sum[2] = 2;
	for (int i = 3; i < maxn; i++) {
		num[i] = num[i-1] + num[i-2];
		sum[i] = sum[i-1] + num[i];
	}
}

int main() {
	init();
	int t;
	scanf("%d", &t);
	while (t--) {
		scanf("%lld", &n);	
		memset(ans, 0, sizeof(ans));			
		int cnt;
		while (n > 0) {
			for (cnt = 1; cnt < 50; cnt++)
				if (n < sum[cnt]) 
					break;
			if (n - sum[cnt-1] == 0)
				cnt--;
			ans[cnt] = 1;
			n -= sum[cnt-1] + 1;
		}
		int flag = 1;
		for (int i = 50; i >= 1; i--) {
			if (ans[i]) {
				printf("1");
				flag = 0;
			}
			else if (!flag)
				printf("0");
		}
		printf("\n");	
	}
	return 0;
}


[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: