HDOJ2062子序列

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

这道题首先是要算出m的最大值和每组的个数
不难得到Mmax=n+n*(n-1)+n*(n-1)*(n-2)+…
前i位相同的数目为Mmax/n/n-1/…/n-i+1

其次是依次求出每位数字,这里要注意的是m如何逐步减小,以n=3,m=9和n=3,m=10为例
m=9时
首先第一位相同的是5个,则9归属第二组,第一位为2
其次5<9<10,则m%5=4,注意第二位为空也是一种情况,所以4-1=3.
第二位相同的有两个所以3归属第二组,因为2已经占用,所以第二位为3,2<3<4,则3%2=1,第三位为空也是一种情况,所以1-1=0,结束。
m=10时
首先第一位相同的是5个,则10归属第二组,第一位为2
其次10%5=0,10/5=2,减去第一组的所有情况,10-5*(2-1)=5注意第二位为空也是一种情况,所以5-1=4.
第二位相同的有两个所以4归属第二组,因为2已经占用,所以第二位为3,4%2=0,4/2=2,减去第一组的所有情况,4-2*(2-1)=2,第三位为空也是一种情况,所以2-1=1,第三位只有一种情况

#include <iostream>
#include<cstdio>
using namespace std;

int main()
{
    int i,j, n,l,x[21],t0;
    long long sum,t,y[20],m;
    while (cin>>n>>m)
    {
        sum = 0; t = 1; l = 0;
        for (i = n; i > 0; i--)
        {
            t *= i;
            sum += t;
        }
        y[0] = sum / n;
        for (i = n - 1; i > 0; i--)
            y[n - i] = y[n - i - 1] / i;
        while (m)
        {
            t0 = m / y[l];
            if (m > y[l]*t0)
                t0++;
            i = 1;
            while(t0)
            {
                for (j = 0; j < l; j++)
                {
                    if (i == x[j])
                        break; 
                }
                if (j==l)
                    t0--;
                i++;
            }
            x[l] = i - 1;
            if (m % y[l] > 0)
                m = m % y[l];
            else
                m -= (m / y[l] - 1) * y[l];
             m--;l++;
        }
        for (i = 0; i < l; i++)
        {
            if (i)
                cout << ' ';
            cout << x[i];
        }
        cout << endl;
    }
   return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值