問題: Codeforces 1638A — Reverse · 한국어 · English
配列は 1..n の順列です。1つの区間を選んで反転し、辞書順で最小の順列を作ります。
左から調べ、p[i] != i + 1 となる最初の位置 i を探します。それより前の位置には、すでに置ける最小の値が入っているため、そのまま固定します。値 i + 1 は順列中にちょうど1回現れるので、その位置を j とします。[i, j] を反転すると i + 1 が最初の不一致位置に移動し、正しい接頭辞は変わりません。よって、この結果が辞書順で最小です。
不一致がなければ順列はすでに整列済みなので、長さ1の区間を反転すればそのままです。最初の不一致と目的の値の位置を探す時間はテストケースごとに O(n)、入力順列を保持する補助領域は O(n) です。
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
import java.io.BufferedInputStream;
import java.io.IOException;
public class Main {
private static final class FastScanner {
private final BufferedInputStream in = new BufferedInputStream(System.in);
private final byte[] buffer = new byte[1 << 16];
private int ptr;
private int len;
private int read() throws IOException {
if (ptr == len) {
len = in.read(buffer);
ptr = 0;
if (len == -1) return -1;
}
return buffer[ptr++];
}
int nextInt() throws IOException {
int c;
do {
c = read();
} while (c <= ' ' && c != -1);
int value = 0;
while (c > ' ') {
value = value * 10 + c - '0';
c = read();
}
return value;
}
}
public static void main(String[] args) throws IOException {
FastScanner fs = new FastScanner();
int tests = fs.nextInt();
StringBuilder answer = new StringBuilder();
while (tests-- > 0) {
int n = fs.nextInt();
int[] permutation = new int[n];
for (int i = 0; i < n; i++) {
permutation[i] = fs.nextInt();
}
int left = 0;
while (left < n && permutation[left] == left + 1) {
left++;
}
if (left < n) {
int right = left;
while (permutation[right] != left + 1) {
right++;
}
while (left < right) {
int value = permutation[left];
permutation[left++] = permutation[right];
permutation[right--] = value;
}
}
for (int i = 0; i < n; i++) {
if (i > 0) answer.append(' ');
answer.append(permutation[i]);
}
answer.append('\n');
}
System.out.print(answer);
}
}