Hdoj 2062

原题链接

描述

Consider the aggregate An= { 1, 2, …, n }. For example, A1={1}, A3={1,2,3}. A subset sequence is defined as a array of a non-empty subset. Sort all the subset sequece of An in lexicography order. Your task is to find the m-th one.

输入

The input contains several test cases. Each test case consists of two numbers n and m ( 0< n<= 20, 0< m<= the total number of the subset sequence of An ).

输出

For each test case, you should output the m-th subset sequence of An in one line.

样例输入

1 1
2 1
2 2
2 3
2 4
3 10

样例输出

1
1
1 2
2
2 1
2 3 1

思路

打表找规律后,能很容易发现递推公式**f(n) = n * f(n-1) + n **, f(n)表示n个数的时候最多有几个。
故利用递推公式预处理,然后把握好一些细节就可以了,有几个要注意的点:
1.每种情况最后一个数后面没有空格(因为这个我PE了一次);
2.确定上一个数字后,下一个数字的情况应当加一,因为存在空集的情况,而算f(n)的时候是没有考虑空集的。

代码

#include <bits/stdc++.h>
#define ll long long
using namespace std;

ll n, m;
ll a[22] = {0, 1};

void myprintf(int f[], int t)
{
	int sum = 0;
	for(int i = 0; i <= 20; i++)
	{
		if(f[i] == 0) sum++;
		if(sum == t)
		{
			printf("%d", i+1);
			m--; n--;
			m %= a[n] + 1;
			if(m > 0) printf(" ");
			f[i] = 1;
			break;
		}
	}
}

int main()
{
	for(int i = 2; i < 21; i++) a[i] = i * a[i - 1] + i;
	while(~scanf("%lld %lld", &n, &m))
	{
		int f[21] = {0};
		while(m > 0 && n >= 0)
		{
			int t = m / (a[n - 1] + 1);
			if(m % (a[n - 1] + 1) == 0) myprintf(f, t);
			else myprintf(f, t + 1); 
		}
		printf("\n");
	}
	return 0;
}
posted @ 2018-01-28 22:51  HackHarry  阅读(179)  评论(0编辑  收藏  举报