結果
問題 |
No.1051 PQ Permutation
|
ユーザー |
![]() |
提出日時 | 2020-05-08 23:23:47 |
言語 | Java (openjdk 23) |
結果 |
WA
(最新)
AC
(最初)
|
実行時間 | - |
コード長 | 2,369 bytes |
コンパイル時間 | 2,379 ms |
コンパイル使用メモリ | 80,216 KB |
実行使用メモリ | 70,004 KB |
最終ジャッジ日時 | 2024-07-05 20:03:46 |
合計ジャッジ時間 | 17,976 ms |
ジャッジサーバーID (参考情報) |
judge3 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 43 WA * 3 |
ソースコード
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.TreeSet; public class Main { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] sa = br.readLine().split(" "); int n = Integer.parseInt(sa[0]); int p = Integer.parseInt(sa[1]); int q = Integer.parseInt(sa[2]); sa = br.readLine().split(" "); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(sa[i]); } br.close(); a = next(a); if (a == null) { System.out.println(-1); return; } int pi = 0; int qi = 0; for (int i = 0; i < n; i++) { if (a[i] == p) { pi = i; } if (a[i] == q) { qi = i; } } if (pi > qi) { if (q == n) { qi--; } if (qi == -1) { System.out.println(-1); return; } TreeSet<Integer> set = new TreeSet<>(); set.add(a[n - 1]); for (int i = a.length - 2; i >= qi; i--) { set.add(a[i]); } while (set.higher(a[qi]) == null) { qi--; if (qi < 0) { System.out.println(-1); return; } set.add(a[qi]); } int[] b = new int[n]; for (int i = 0; i < qi; i++) { b[i] = a[i]; } b[qi] = set.higher(a[qi]); set.remove(b[qi]); set.add(a[qi]); boolean flg = b[qi] == p; while (!set.isEmpty()) { qi++; int o = set.pollFirst(); if (!flg && o == q) { int o2 = set.pollFirst(); b[qi] = o2; set.add(o); if (o2 == p) { flg = true; } } else { b[qi] = o; if (o == p) { flg = true; } } } a = b; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { sb.append(a[i]).append(' '); } sb.deleteCharAt(sb.length() - 1); System.out.println(sb.toString()); } static int[] next(int[] a) { TreeSet<Integer> set = new TreeSet<>(); set.add(a[a.length - 1]); for (int i = a.length - 2; i >= 0; i--) { if (a[i] > a[i + 1] || set.higher(a[i]) == null) { set.add(a[i]); } else { int[] b = new int[a.length]; for (int j = 0; j < i; j++) { b[j] = a[j]; } b[i] = set.higher(a[i]); set.remove(b[i]); set.add(a[i]); Integer[] arr = set.toArray(new Integer[0]); for (int j = 0; j < arr.length; j++) { b[i + 1 + j] = arr[j]; } return b; } } return null; } }