Subset sequence(难理解)
题目描述:
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
通过答案:
#include<stdio.h>
int main()
{
int n,i,group;
int s[21]; //每组首字母
__int64 m;
__int64 c[21]={0}; //每组个数
for(i=1;i<21;i++){
c[i]=(i-1)*c[i-1]+1;
}
while(scanf("%d%I64d",&n,&m)!=EOF){
for(i=0;i<21;i++){ //初始化首元素
s[i]=i;
}
while(n--&&m){
if (group= m / c[n+1] + ((m % c[n+1]) ? 1 : 0)) //计算组数
{
printf("%d", s[group]);
for (i = (int)group; i <= n; s[i]=s[i+1], i++); //删除首元素
m -= (group- 1) * c[i] + 1; //计算在第几个
if(m==0){
printf("\n");
}else{
printf(" ");
}
}
}
}
return 0;
}