permutation 1

题目链接

题意

找出一个n的全排列,让其后向差分序列字典序最小。

思路

1≤K≤min(10000,n!),注意到这一点,我们可以知道当n大于8的时候,我们前面几项应该是n,1,2,3,4,…直到最后八项。
最后八项怎么确定呢,看到这个k范围很小,不妨枚举出所有全排列,然后排个序去找第k大。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#ifndef ONLINE_JUDGE
#define dbg(x...) \
do \
{ \
cout << "\033[33;1m" << #x << "->"; \
err(x); \
} while (0)
void err()
{
cout << "\033[39;0m" << endl;
}
template <template <typename...> class T, typename t, typename... A>
void err(T<t> a, A... x)
{
for (auto v : a) cout << v << ' ';
err(x...);
}
template <typename T, typename... A>
void err(T a, A... x)
{
cout << a << ' ';
err(x...);
}
#else
#define dbg(...)
#endif

const int N = 25;
const int maxn = 100005;
int arr[maxn][25];
int cha[maxn][25];
int id[maxn];
int fac[10];
int a[N];
bool cmp1(int x, int y)
{
for (int i = 1;; i++)
{
if (cha[x][i] < cha[y][i])
return true;
if (cha[x][i] > cha[y][i])
return false;
}
return false;
}

int main()
{
int T;
fac[0] = 1;
for (int i = 1; i <= 8; i++)
fac[i] = fac[i - 1] * i;
scanf("%d", &T);
while (T--)
{
int n, k;
scanf("%d%d", &n, &k);
int state = 0;
int res = n;
int pre = -1;
if (n > 8)
{
printf("%d ", n);
state |= 1 << (n - 1), pre = n;
for (int i = 1; n - i - 1 >= 8; i++)
printf("%d ", i), state |= 1 << (i - 1), pre = i;
res = 8;
}
int cur = 0;
for (int i = 0; i < n; i++)
{
if (!((1 << i) & state))
a[cur++] = i + 1;
}
for (int i = 1; i <= fac[res]; i++)
{
id[i] = i;
}
int t = 0;
if (pre == -1)
{
do
{
t++;
for (int i = 0; i < cur; i++)
arr[t][i] = a[i];
} while (next_permutation(a, a + cur));
for (int i = 1; i <= fac[res]; i++)
{
for (int j = 1; j < res; j++)
cha[i][j] = arr[i][j] - arr[i][j - 1];
}
sort(id + 1, id + fac[res] + 1, cmp1);
/* puts("askjdal");
for (int i = 1; i <= fac[res]; i++)
{
for (int j = 0; j < res; j++)
printf("%d ", arr[id[i]][j]);
putchar('\n');
}
//puts("ajksdfhajkhdfj");*/
for (int i = 1; i <= res; i++)
printf("%d%c", arr[id[k]][i - 1], i == res ? '\n' : ' ');
}
else
{
do
{
t++;
arr[t][0] = pre;
for (int i = 0; i < cur; i++)
arr[t][i + 1] = a[i];
} while (next_permutation(a, a + cur));
for (int i = 1; i <= fac[res]; i++)
{
for (int j = 1; j <= res; j++)
cha[i][j] = arr[i][j] - arr[i][j - 1];
}
sort(id + 1, id + fac[res] + 1, cmp1);
for (int i = 1; i <= res; i++)
printf("%d%c", arr[id[k]][i], i == res ? '\n' : ' ');
}
}
return 0;
}
0%