Hdoj 2062

本文介绍了一个关于子集序列的算法问题,该问题要求在字典序下找到第m个子集序列。通过分析和使用递推公式进行预处理,文章提供了一个有效的解决方案,并附带了完整的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题链接

描述

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;
}

转载于:https://www.cnblogs.com/HackHarry/p/8372051.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值