Codeforces 513B2 Permutations

本文介绍了一个关于求解特定条件下的最优排列的问题,并提供了一种有效的算法实现。通过分析排列组合的特点,利用二进制分解的方法构造出了字典序第m大的序列。

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

You are given a permutation p of numbers 1, 2, …, n. Let’s define f(p) as the following sum:

Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p).

Input
The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p).

The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.

In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold.
In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold.
Output
Output n number forming the required permutation.

Sample test(s)
input
2 2
output
2 1
input
3 2
output
1 3 2
Note
In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order.

解题思路:首先我们应该知道如何求解最优方案,总共存在n*(n+1)/2对,因此我们最优的方案应该让越小的数影响的对数越小。因此1只能放在1或n的位置处,在1放好之后在将2放在剩余位置的两端,依次下去可以得到最优解,很容可以得知这样的最优解的个数为2^(n-1),因此要求解字典序第m大序列,按照二进制分解构造即可。

#include <cmath>
#include <ctime>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>
#include <vector>
#include <deque>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <utility>
#include <algorithm>
#include <functional>
using namespace std;
typedef long long ll;
int bit[60];
int ans[60];

int main() {

    //freopen("aa.in", "r", stdin);

    int n;
    ll m;
    cin >> n >> m;
    m--;
    for(int i = 0; i < n; ++i) {
        if((1LL<<i)&m) {
            bit[i] = 1;
        } else {
            bit[i] = 0;
        }
    }
    int s[2];
    s[0] = 1;
    s[1] = n;
    int x = 1;
    for(int i = n - 2; i >= 0; --i) {
        if(bit[i] == 1) {
            ans[s[1]] = x;
            s[1]--;
        } else {
            ans[s[0]] = x;
            s[0]++;
        }
        x++;
    }
    ans[s[0]] = n;
    for(int i = 1; i <= n; ++i) {
        printf("%d ", ans[i]);
    }
    printf("\n");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值