Codeforces 513B2 Permutations

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;
}
發佈了230 篇原創文章 · 獲贊 2 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章