Codeforces 513B2 Permutations

来源:互联网 发布:小游戏源代码java 编辑:程序博客网 时间:2024/04/29 08:06

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;}
0 0
原创粉丝点击