permutation 1
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 524 Accepted Submission(s): 212
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
Source
2019 Multi-University Training Contest 5
思路:因为k最大为1e4,所以可以以根据是否大于8来分类讨论,当当于8时,直接按照全排列依次取数即可,而小于8时,则可以将所有情况枚举,然后排序得到答案。
AC代码:
#include <bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define per(i,a,b) for(int i=a;i>=b;i--)
typedef long long ll;
typedef vector<ll> vec;
//typedef vector<vec> mat;
const ll MOD = 1000000007;//根据需要更改
const int MAXN = 50;
const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3f;
struct P{
int a[11];
int b[11];
}v[500000];
int fac[MAXN];
int ans[MAXN];
int T, n, k;
bool cmp(P a, P b){
for(int i = 0; i < n - 1; i++) {
if(a.b[i] < b.b[i]) return true;
if(a.b[i] > b.b[i]) return false;
}
return false;
}
int main()
{
//std::ios::sync_with_stdio(false);
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
// fac[0] = 1;
// rep(i, 1, 20){
// if(i > 8) fac[i] = INF;
// else fac[i] = fac[i-1]*i;
// printf("%d\n", fac[i]);
// }
scanf("%d", &T);
while(T--){
scanf("%d%d", &n, &k);
if(n > 8){
ans[0] = n;
rep(i, 1, n-1){
ans[i] = i;
}
int cnt = 0;
do{
cnt++;
if(cnt == k) break;
}while(next_permutation(ans, ans+n));
rep(i, 0, n-1){
if(i!=0) putchar(' ');
printf("%d", ans[i]);
}
putchar('\n');
}else{
rep(i, 0, n-1){
ans[i] = i+1;
}
int cnt = 0;
rep(i, 0, INF){
rep(j, 0, n-1){
v[i].a[j] = ans[j];
if(j>0) v[i].b[j-1] = v[i].a[j] - v[i].a[j-1];
}
v[i].b[n-1] = -INF;
cnt++;
if(!next_permutation(ans, ans+n)) break;
}
sort(v, v+cnt, cmp);
k--;
rep(i, 0, n-1){
if(i!=0) putchar(' ');
printf("%d", v[k].a[i]);
}
putchar('\n');
}
}
return 0;
}
/*
5
3
7 7 7
0 7 5
*/