版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wangke1998/article/details/80781122
Subset sequence
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 7649 Accepted Submission(s): 3492
Problem Description
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.
Input
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 ).
Output
For each test case, you should output the m-th subset sequence of An in one line.
Sample Input
1 1 2 1 2 2 2 3 2 4 3 10
Sample Output
1 1 1 2 2 2 1 2 3 1
Author
LL
Source
#include<stdio.h>
int main()
{
int n,i,t;
int s[21];
long long m;
long long g[21]={0};
for(i=1;i<21;i++)
g[i]=(i-1)*g[i-1]+1;//推导出来的g(n) = (n-1) * g(n-1) + 1
while(scanf("%d%lld",&n,&m)!=EOF)
{
for(i=0;i<21;i++)
s[i]=i;//每循环一次就重新归位每组首元素
while(n>0&&m>0)
{
t=m/g[n]+(m%g[n]>0?1:0);
if(t>0)//得到第m个子集在分组后的第t组
{
printf("%d",s[t]);
for(i=t;i<=n;i++)
s[i]=s[i+1];//或s[i]+=1,我们发现,第n组中,第2个元素在第n个时变为他的下一个数
m-=((t-1)*g[n]+1);//减去(t-1组总子集数+1)m变为表示在剩余子集中位于第几个
putchar(m==0?'\n':' ');
}
n--;
}
}
return 0;
}
PS:参照了别人的博客,才理解了这个题。
解题思路:
首先我们来看看An一共有多少个子集。
n=1时,只有{1}一个子集合也许你发现规律了。An子集合的个数为:n=2时,就有:
{1}, {2},
{1, 2}, {2, 1}
4个子集合。n=3时,有
{1}, {2}, {3},
{1, 2}, {1, 3}, {2, 1}, {2, 3}, {3, 1}, {3, 2},
{1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2}, {3, 2, 1}
C 1 n ·A 1 1 + C 2 n ·A 2 2 + ... + C n n ·A n n
这个公式是对的。但我们换个角度看。
n=3时,有不难发现,An可以按首数字分成n组,而每组里除了第一项,剩下的就是An-1的子集合了。
{1}
{1, 2}
{1, 2, 3}
{1, 3}
{1, 3, 2}{2}
{2, 1}
{2, 1, 3}
{2, 3}
{2, 3, 1}{3}
{3, 1}
{3, 1, 2}
{3, 2}
{3, 2, 1}
∴f(n) = n[f(n-1) + 1]
f(1) = 1
其实就是对于每一位i的下一位i-1,需要有两种考虑方式,一是后面为空作为第一个出现,二是后面不空即对第i位后面有i-1个数可以选择,也就是从2--i ,对于每个位若后面只有一个可选的情况此时算上空位总共i个。但是如果考虑每一位后面就要相乘,即递归关系。
不难得出:
g(n) = f(n) / n //g(n)为每一位后面总共有多少种排列(按序)1
∵f(n) = n[f(n-1) + 1] //2
∴g(n) = n[f(n-1) + 1] / n = f(n-1) + 1 //3
∵f(n-1) = (n-1) * g(n-1) //g(n) =f(n-1) + 1 //4
∴g(n) = (n-1) * g(n-1) + 1 //代入3式 //5