2019 Multi-University Training Contest 5 - permutation 1

permutation 1

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 1055    Accepted Submission(s): 489


 

Problem Description

A sequence of length n is called a permutation if and only if it's composed of the first n positive integers and each number appears exactly once.

Here we define the "difference sequence" of a permutation p1,p2,…,pn as p2−p1,p3−p2,…,pn−pn−1. In other words, the length of the difference sequence is n−1 and the i-th term is pi+1−pi

Now, you are given two integers N,K. Please find the permutation with length N such that the difference sequence of which is the K-th lexicographically smallest among all difference sequences of all permutations of length N.

 

 

Input

The first line contains one integer T indicating that there are T tests.

Each test consists of two integers N,K in a single line.

* 1≤T≤40

* 2≤N≤20

* 1≤K≤min(104,N!)

 

 

Output

For each test, please output N integers in a single line. Those N integers represent a permutation of 1 to N, and its difference sequence is the K-th lexicographically smallest.

 

Sample Input

7

3 1

3 2

3 3

3 4

3 5

3 6

20 10000

 

Sample Output

3 1 2

3 2 1

2 1 3

2 3 1

1 2 3

1 3 2

20 1 2 3 4 5 6 7 8 9 10 11 13 19 18 14 16 15 17 12

 

题目意思是:给定N和K; 原序列的数字为1~N,那么这N个数字就有 N! 种排列方式,排列的顺序是按照题目中的要求(差分序列在字典学上最小,依次排序)

然后输出第 k 个原序列.例如下图:(已经按照差分序列在字典学上按小到大排列)

 

2019 Multi-University Training Contest 5 - permutation 1_第1张图片

 

题解AC代码:

#include
#include
#include
using namespace std;
#define ll long long
const int INF = 0x3f3f3f3f;
const int MOD = 1e9;

#include
#include
const int SIZE = 50;
int n, k;
int d[SIZE], use[SIZE];

//此搜索函式在填值时只填相对的值,到最后一步才决定每个位置真正的值

bool dfs(int id, int low, int hi) {  
    if(id == n) {
        k--;
        if(!k) {
            for(int i = 0; i < n; i++) {
                if(i != 0) printf(" ");
                printf("%d", d[i] - low + 1);
            }
            puts("");
            return 1;
        }
        return 0;
    }
    for(int i = hi - n + 1; i <= low + n - 1; i++) {
        if(use[i]) continue;
        use[i] = 1;
        d[id] = i;
        if(dfs(id + 1, min(low,i), max(hi,i))) {
            use[i] = 0;
            return 1;
        }
    
        use[i] = 0;
    }
    return 0;
}

int main() {   
    int T;
    scanf("%d", &T);
    while(T--) {
        scanf("%d%d", &n, &k);
        d[0] = n;
        use[n] = 1;
        dfs(1, n, n);
        use[n] = 0;
    }
    return 0;
}

 

你可能感兴趣的:(2019 Multi-University Training Contest 5 - permutation 1)