permutation 1
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,把n个数全排序,有很多种不同的排列方式(如3 1 2,2 1 3),输出第k种排列方式。题目给出的排序规则:相邻两个数为一组,从第一组开始,相邻两个数的差越小排越前。例子输出中的3 1 2,相减得到的是 -2,1比3 2 1的-1 -1,前者第一组数已经比后者小了,所以不需要考虑后面的内容,3 1 2排在3 2 1前头。
这个样例给的实在太心机了,我看到这道题的时候并没有太读懂题意就开始抖机灵,以为是第一位从大到小排,后面的位是尽量从小到大排,写完代码之后用20的那个样例测试发现能得到正确的答案就提交了。WA了以后以为是自己哪里没有处理,各种修改边界类型,然后我的队友告诉我题意理解错了……
题解说这道题数据很小,可以直接爆搜解决问题,时间复杂度是O(k×n2)。
代码
#include<bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 40+5;
typedef long long ll;
#define debug printf("debug\n");
int t,n;
ll k;
bool vis[maxn];
int ans[maxn];
bool dfs(int pos, int pre, int l, int r) {
if(pos == n) {
k--;
if(!k) { //所有位枚举完才输出
for(int i=0; i<n; i++) {
cout << ans[i] - l + 1;
if(i<n-1) {
cout << " ";
} else {
puts("");
}
}
return true;
}
return false;
}
for(int i=1-n; i<=n-1; i++) { //枚举差值
if(vis[20+i+pre]) { //加20为了防止负数出现什么奇怪的问题
continue;
}
vis[20+i+pre] = true;
ans[pos] = i+pre;
if(max(i+pre,r) - min(l,i+pre) <= n-1) { //判断是否符合数据要求
ans[pos] = i + pre;
if(dfs(pos+1, i+pre, min(i+pre,l), max(i+pre,r) ) ) {
vis[20+i+pre]=false;
return true;
}
}
vis[20+i+pre]=false;
}
return false;
}
int main() {
while(cin >> t) {
while(t--) {
cin >> n >> k;
memset(vis, 0, sizeof(vis));
vis[20+n]=true;
ans[0]=n;
dfs(1,n,n,n);
}
}
}