AcWing 1588. 插入还是堆排序-java
原题链接
中等
作者:
Astarion
,
2021-03-09 09:06:45
,
所有人可见
,
阅读 334
import java.io.*;
class Main {
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
OutputStreamWriter osw = new OutputStreamWriter(System.out);
BufferedWriter out = new BufferedWriter(osw);
int n = Integer.parseInt(in.readLine());
int[] o = new int[n + 1];
int[] t = new int[n + 1];
String[] strs = in.readLine().split(" ");
for (int i = 1; i <= n; i++) o[i] = Integer.parseInt(strs[i - 1]);
strs = in.readLine().split(" ");
for (int i = 1; i <= n; i++) t[i] = Integer.parseInt(strs[i - 1]);
boolean isInsert = true;
int p = 1;
while (p <= n && t[p] <= t[p + 1]) p++;
//插入排序,前缀应是递增的,后缀应该与原序列相同
for (int i = p + 1; i <= n; i++)
if (t[i] != o[i]) {
isInsert = false;
break;
}
if (isInsert) {
out.write("Insertion Sort\n");
int i = p + 1;
int x = t[i];
while (t[i - 1] > x) {
t[i] = t[i - 1];
i--;
}
t[i] = x;
} else {
out.write("Heap Sort\n");
//堆排序每次迭代后,第一个元素是未排序部分最大值,后缀是已排序部分
int size = n;
while (t[size] >= t[1]) size--;
int temp = t[size];
t[size--] = t[1];
t[1] = temp;
for (int i = 1; i <= size / 2; ) {
int x = i;
if (t[i * 2] > t[i]) x = i * 2;
if (i * 2 + 1 <= size && t[i * 2 + 1] > t[x]) x = i * 2 + 1;
if (x == i) break;
temp = t[i];
t[i] = t[x];
t[x] = temp;
i = x;
}
}
for (int i = 1; i <= n; i++) {
out.write(t[i]+" ");
}
in.close();
isr.close();
out.flush();
out.close();
osw.close();
}
}