Subset sequence
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 8387 Accepted Submission(s): 3794
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
校庆杯Warm Up
Recommend
linle
题目简述:
给出一个数字n,对应集合An{1,2,3,… …,n},求其按字典排序的子集中的第m个。
例如,A3的排列顺序如下:
{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}
问题分析:
我们可以把An的排序分成n组,每组的第一个数字即为该组的组号。例如A3可以分为3组。
然后重点来了,可以看出将A3每组第一列去掉后 剩下的其实就是是n组A2的排序,但是因为第x组的开头是x,因为一个数列中数字不重复,所以从第x个数开始,用x+1代替x;
第一组的第一个数字是1,从1开始,2代替1,3代替2
{1}->{2}
{1,2}->{2,3}
{2}->{3}
{2,1}->{3,2}
第二组的第一个数字是2,所以从2开始,3代替2
{1}->{1}
{1,2}->{1,3}
{2}->{3}
{2,1}->{3,1}
第三组的第一个数字是3,因为A2中没有3,所以不需要替换
{1}->{1}
{1,2}->{1,2}
{2}->{2}
{2,1}->{2,1}
可以看出An的排序去掉第一列后其实就是n组An-1的排序,而第An-1组去掉第一行后又是第An-2的排序,以此类推。
只不过因因为第x组开头占用了数字x,所以这组中,x及比x大的数字用x+1来替代x。
例如第6组中因为第一个数字必定是6,所以该组后面的6用7代替,7用8代替,以此类推。
第m组数第一个数字就看m在An的第几组,第二个就看m在An-1的第几组,以此类推。
几个比较关键的点是:
1.An排序的总行数f[n]=n*(f[n-1]+1),An每组的行数等于f[n]/n,所以g[n]=(n-1)*g[n-1]+1。
2.这里的m比较大,需要用long long或者__int64。
3.计算m对应的组数时需要使用进一除法。例如A3中第9,10行都属于第2组,但在c++中默认是不满一就退一的,10/5=2,9/5=1。所以需要实现进一除法。
写代码到时候用n叫a,m叫b,懒得改了,将就着看吧。。。
代码实现:
#include<bits/stdc++.h>
using namespace std;
int main()
{
long long g[22]={0};
g[1]=1;
int a,i,t,s[22];
for(i=1;i<=20;i++) g[i]=(i-1)*g[i-1]+1;
long long b;
while(scanf("%d%lld",&a,&b)!=EOF)
{
for(i=0;i<21;i++) s[i]=i;
while(a>0&&b>0)
{
t=(b+g[a]-1)/g[a];//求出b对应的组号,进一除法
if(t>0)
{
printf("%d",s[t]);
for(i=t;i<=a;i++) s[i]=s[i+1];
b-=((t-1)*g[a]+1);
printf("%c",b==0?'\n':' ');
}
a--;
}
}
}