結果
| 問題 | No.5026 Spectrum Router |
| コンテスト | |
| ユーザー |
37zigen
|
| 提出日時 | 2026-11-23 22:50:41 |
| 言語 | Java (openjdk 27.0.1.0.3 + ACL) |
| 結果 |
AC
不安定
|
| 実行時間 | 1,932 ms / 2,000 ms |
| + 573µs | |
| コード長 | 38,482 bytes |
| 記録 | |
| コンパイル時間 | 3,750 ms |
| コンパイル使用メモリ | 121,888 KB |
| 実行使用メモリ | 61,548 KB |
| スコア | 1,453,729 |
| 最終ジャッジ日時 | 2026-11-23 22:57:12 |
| 合計ジャッジ時間 | 105,966 ms |
|
ジャッジサーバーID (参考情報) |
judge2_0 / judge5_0 |
| 純コード判定しない問題か言語 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 50 |
ソースコード
public class Main implements java.lang.Runnable {
public static void main(java.lang.String[] args) throws java.io.IOException {
// Runtime runtime = Runtime.getRuntime();
// new Thread(null, new Main(), "MainThreadWithLargeStack", (1024 * 1024) *1024).start();
new Main().run();
// long usedMemory = runtime.totalMemory() - runtime.freeMemory();
// System.err.printf("使用メモリ: %.2f MB%n", usedMemory / 1024.0 / 1024.0);
MyPrintWriter.getInstance().flush();
}
java.util.Random rnd = new java.util.Random();
@java.lang.Override
public void run() {
FastScanner sc = FastScanner.getInstance();
MyPrintWriter pw = MyPrintWriter.getInstance();
int N = sc.nextInt();
int[] A = sc.nextInts(4 * N);
long startTime = java.lang.System.nanoTime();
ArrayUtils.decrementAll(A);
char[][] S = new char[N][N];
ArrayUtils.fill(S, '0');
MinimumCostFlow mf = new MinimumCostFlow((4 * N) + 2);
for (int i = 0; i < N; i++) {
mf.addEdge(i, ((3 * N) - 1) - i, cost(i, A[i], ((3 * N) - 1) - i, A[((3 * N) - 1) - i]), 1);
}
for (int i = 0; i < N; i++) {
for (int j = N; j < (4 * N); j++) {
if (((2 * N) <= j) && (j < (3 * N))) {
continue;
}
mf.addEdge(i, j, cost(i, A[i], j, A[j]), 1);
}
}
int source = 4 * N;
int sink = source + 1;
for (int i = 0; i < N; i++) {
mf.addFixedFlowEdge(source, i, 0, 1);
}
for (int i = N; i < (4 * N); i++) {
mf.addEdge(i, sink, 0, 1);
}
mf.minCostFlowAtMost(source, sink, N);
for (int i = 0; i < N; i++) {
for (var e : mf.g[i]) {
if (e.flow > 0) {
if ((N <= e.to) && (e.to < (2 * N))) {
S[e.to - N][i] = '2';
}
if (((3 * N) <= e.to) && (e.to < (4 * N))) {
S[(N - 1) - (e.to - (3 * N))][i] = '1';
}
}
}
}
// pw.println(S);
long TL = (1900L * 1000) * 1000;
long curScore = eval(A, S);
for (int T = 0; T < 1000000; T++) {
if ((T % 100) == 0) {
long dt = java.lang.System.nanoTime() - startTime;
if (dt >= TL) {
break;
}
}
int i = rnd.nextInt(N);
int j = rnd.nextInt(N);
int v = rnd.nextInt(3);
if ((S[i][j] - '0') == v) {
continue;
}
char pre = S[i][j];
S[i][j] = ((char) ('0' + v));
long score = eval(A, S);
if (score > curScore) {
S[i][j] = pre;
} else {
curScore = score;
}
}
pw.println(S);
}
int cost(int i0, int v0, int i1, int v1) {
int d0 = java.lang.Math.abs(i0 - v1);
int d1 = java.lang.Math.abs(i1 - v0);
return d0 + d1;
}
long eval(int[] A, char[][] S) {
int N = S.length;
int[] B = new int[4 * N];
int[] di = new int[]{ 1, 0, -1, 0 };
int[] dj = new int[]{ 0, -1, 0, 1 };
for (int t = 0; t < A.length; t++) {
int dir = t / N;// ↓、←、↑、→
int i;
int j;
if (t < N) {
i = 0;
j = t;
} else if (t < (2 * N)) {
i = t % N;
j = N - 1;
} else if (t < (3 * N)) {
i = N - 1;
j = (N - 1) - (t % N);
} else {
i = (N - 1) - (t % N);
j = 0;
}
while (true) {
if (S[i][j] == '1') {
if (dir == 0) {
dir = 1;
} else if (dir == 1) {
dir = 0;
} else if (dir == 2) {
dir = 3;
} else if (dir == 3) {
dir = 2;
}
} else if (S[i][j] == '2') {
// ↓、←、↑、→
if (dir == 0) {
dir = 3;
} else if (dir == 3) {
dir = 0;
} else if (dir == 2) {
dir = 1;
} else if (dir == 1) {
dir = 2;
}
}
i += di[dir];
j += dj[dir];
if (!((((0 <= i) && (i < N)) && (0 <= j)) && (j < N))) {
if (i == (-1)) {
B[j] = A[t];
} else if (i == N) {
B[((3 * N) - 1) - j] = A[t];
} else if (j == (-1)) {
B[((4 * N) - 1) - i] = A[t];
} else if (j == N) {
B[N + i] = A[t];
}
break;
}
}
}
return Permutation.inversion(B);
}
}
class ArrayUtils {
public static void decrementAll(int[] a) {
for (int i = 0; i < a.length; i++) {
a[i]--;
}
}
public static void fill(char[][] a, char v) {
ArrayUtils2D.fill(a, v);
}
/**
* *
* a[i] = max a となる最小のiを返す。
*
* @param a
* @return */
public static int argMax(long[] a) {
int ret = 0;
for (int i = 0; i < a.length; ++i) {
if (a[i] > a[ret]) {
ret = i;
}
}
return ret;
}
public static long max(long[] a) {
long ret = java.lang.Long.MIN_VALUE;
for (int i = 0; i < a.length; ++i) {
ret = java.lang.Math.max(ret, a[i]);
}
return ret;
}
}
/**
* 2次元配列操作のユーティリティクラス。
*/
class ArrayUtils2D {
public static void fill(char[][] a, char v) {
for (int i = 0; i < a.length; ++i) {
for (int j = 0; j < a[i].length; ++j) {
a[i][j] = v;
}
}
}
}
/**
* モノイド作用に関する離散対数問題を解く。
* https://maspypy.com/%e3%83%a2%e3%83%8e%e3%82%a4%e3%83%89%e4%bd%9c%e7%94%a8%e3%81%ab%e9%96%a2%e3%81%99%e3%82%8b%e9%9b%a2%e6%95%a3%e5%af%be%e6%95%b0%e5%95%8f%e9%a1%8c
*/
class DiscreteLogarithm {
/**
* Solve min_n f^n s = t (0 <= n <= maxSearch) with custom Hash Strategy.
*/
public static <S, F> long discreteLog(F baby, F giant, S s, S t, java.util.function.BiFunction<F, S, S> mapping, long maxSearch, int giantStride, Hash.Strategy<S> strategy) {
if (strategy == null) {
if (java.util.Objects.equals(s, t)) {
return 0;
}
} else if (strategy.equals(s, t)) {
return 0;
}
if (maxSearch <= 0) {
return -1;
}
OpenHashSet<S> ys = (strategy == null) ? new OpenHashSet<>() : new OpenHashSet<>(strategy);
{
S yt = t;
for (int i = 0; i < giantStride; ++i) {
ys.add(yt);
yt = mapping.apply(baby, yt);
}
}
int numFails = 0;
S cur = s;
for (long k = 1; ; ++k) {
S nxt = mapping.apply(giant, cur);
if (ys.contains(nxt)) {
for (int i = 1; i <= giantStride; ++i) {
cur = mapping.apply(baby, cur);
boolean match = (strategy == null) ? java.util.Objects.equals(cur, t) : strategy.equals(cur, t);
if (match) {
long ret = ((k - 1) * giantStride) + i;
return ret <= maxSearch ? ret : -1;
}
}
++numFails;
} else {
cur = nxt;
}
if ((numFails >= 2) || ((k * giantStride) > maxSearch)) {
return -1;
}
}
}
/**
* Solve min_n f^n s = t (0 <= n <= maxSearch).
*/
public static <S, F> long discreteLog(F f, S s, S t, java.util.function.BiFunction<F, S, S> mapping, java.util.function.BiFunction<F, F, F> composition, long maxSearch) {
return DiscreteLogarithm.discreteLog(f, s, t, mapping, composition, maxSearch, null);
}
/**
* Solve min_n f^n s = t (0 <= n <= maxSearch) with custom Hash Strategy.
*/
public static <S, F> long discreteLog(F f, S s, S t, java.util.function.BiFunction<F, S, S> mapping, java.util.function.BiFunction<F, F, F> composition, long maxSearch, Hash.Strategy<S> strategy) {
boolean match = (strategy == null) ? java.util.Objects.equals(s, t) : strategy.equals(s, t);
if (match) {
return 0;
}
if (maxSearch <= 0) {
return -1;
}
final int giantStride = ((int) (java.lang.Math.ceil(java.lang.Math.sqrt(maxSearch))));
if (giantStride <= 0) {
return match ? 0 : -1;
}
F giant = f;
F tmp = f;
for (int n = giantStride - 1; n > 0; n >>= 1) {
if ((n & 1) == 1) {
giant = composition.apply(giant, tmp);
}
tmp = composition.apply(tmp, tmp);
}
return DiscreteLogarithm.discreteLog(f, giant, s, t, mapping, maxSearch, giantStride, strategy);
}
}
class FastScanner {
private static FastScanner instance = null;
private final java.io.InputStream in = java.lang.System.in;
private final byte[] buffer = new byte[1 << 16];
private int ptr = 0;
private int buflen = 0;
private FastScanner() {
}
public static FastScanner getInstance() {
if (FastScanner.instance == null) {
FastScanner.instance = new FastScanner();
}
return FastScanner.instance;
}
private boolean hasNextByte() {
if (ptr < buflen) {
return true;
}
ptr = 0;
try {
buflen = in.read(buffer);
} catch (java.io.IOException e) {
e.printStackTrace();
}
return buflen > 0;
}
private int readByte() {
if (hasNextByte()) {
return buffer[ptr++];
} else {
return -1;
}
}
private boolean isPrintableChar(int c) {
return (33 <= c) && (c <= 126);
}
public boolean hasNext() {
while (hasNextByte() && (!isPrintableChar(buffer[ptr]))) {
ptr++;
}
return hasNextByte();
}
public long nextLong() {
if (!hasNext()) {
throw new java.util.NoSuchElementException();
}
long n = 0;
boolean minus = false;
int b = readByte();
if (b == '-') {
minus = true;
b = readByte();
}
while ((b >= '0') && (b <= '9')) {
// n = n * 10 + (b - '0');
n = ((n << 1) + (n << 3)) + (b - '0');
b = readByte();
}
return minus ? -n : n;
}
public int nextInt() {
return ((int) (nextLong()));
}
public int[] nextInts(int n) {
int[] a = new int[n];
for (int i = 0; i < n; ++i) {
a[i] = nextInt();
}
return a;
}
}
class Hash {
public interface Strategy<K> {
int hashCode(K o);
boolean equals(K a, K b);
}
public static <K> Hash.Strategy<K> defaultStrategy() {
return new Hash.Strategy<K>() {
@java.lang.Override
public int hashCode(K o) {
if (o instanceof int[]) {
return java.util.Arrays.hashCode(((int[]) (o)));
}
if (o instanceof long[]) {
return java.util.Arrays.hashCode(((long[]) (o)));
}
if (o instanceof char[]) {
return java.util.Arrays.hashCode(((char[]) (o)));
}
if (o instanceof boolean[]) {
return java.util.Arrays.hashCode(((boolean[]) (o)));
}
if (o instanceof byte[]) {
return java.util.Arrays.hashCode(((byte[]) (o)));
}
if (o instanceof short[]) {
return java.util.Arrays.hashCode(((short[]) (o)));
}
if (o instanceof float[]) {
return java.util.Arrays.hashCode(((float[]) (o)));
}
if (o instanceof double[]) {
return java.util.Arrays.hashCode(((double[]) (o)));
}
if (o instanceof java.lang.Object[]) {
return java.util.Arrays.deepHashCode(((java.lang.Object[]) (o)));
}
if (o instanceof java.lang.Long x) {
x ^= x >>> 33;
x *= 0xff51afd7ed558ccdL;
x ^= x >>> 33;
x *= 0xc4ceb9fe1a85ec53L;
x ^= x >>> 33;
return x.intValue();
}
return o.hashCode();
}
@java.lang.Override
public boolean equals(K a, K b) {
if ((a instanceof int[]) && (b instanceof int[])) {
return java.util.Arrays.equals(((int[]) (a)), ((int[]) (b)));
}
if ((a instanceof long[]) && (b instanceof long[])) {
return java.util.Arrays.equals(((long[]) (a)), ((long[]) (b)));
}
if ((a instanceof char[]) && (b instanceof char[])) {
return java.util.Arrays.equals(((char[]) (a)), ((char[]) (b)));
}
if ((a instanceof boolean[]) && (b instanceof boolean[])) {
return java.util.Arrays.equals(((boolean[]) (a)), ((boolean[]) (b)));
}
if ((a instanceof byte[]) && (b instanceof byte[])) {
return java.util.Arrays.equals(((byte[]) (a)), ((byte[]) (b)));
}
if ((a instanceof short[]) && (b instanceof short[])) {
return java.util.Arrays.equals(((short[]) (a)), ((short[]) (b)));
}
if ((a instanceof float[]) && (b instanceof float[])) {
return java.util.Arrays.equals(((float[]) (a)), ((float[]) (b)));
}
if ((a instanceof double[]) && (b instanceof double[])) {
return java.util.Arrays.equals(((double[]) (a)), ((double[]) (b)));
}
if ((a instanceof java.lang.Object[]) && (b instanceof java.lang.Object[])) {
return java.util.Arrays.deepEquals(((java.lang.Object[]) (a)), ((java.lang.Object[]) (b)));
}
return a.equals(b);
}
};
}
}
/**
* 流量をFとしてO(F(N+M)log(N+M))。負辺は最初に全て流しきるため、負辺の流量F'が、答えに必要なくてもFに加算される。F'を計算量から消したい場合は、最初から簡約費用にする。
*/
class MinimumCostFlow {
int N;
public java.util.ArrayList<MinimumCostFlow.Edge>[] g;
public java.util.ArrayList<MinimumCostFlow.Edge>[] ig;
public long[] excess;
public long[] potential;
long INF = java.lang.Long.MAX_VALUE / 3;
MinimumCostFlow.Edge[] incommingShortestPathEdge;
long[] d;
long base = 0;
@java.lang.SuppressWarnings("unchecked")
public MinimumCostFlow(int N) {
this.N = N;
g = new java.util.ArrayList[this.N];
ig = new java.util.ArrayList[this.N];
excess = new long[this.N];
potential = new long[this.N];
d = new long[this.N];
incommingShortestPathEdge = new MinimumCostFlow.Edge[this.N];
for (int i = 0; i < this.N; ++i) {
g[i] = new java.util.ArrayList<>();
ig[i] = new java.util.ArrayList<>();
}
}
public class Edge {
public int from;
public int to;
public long cost;
public long cap;
public long flow = 0;
MinimumCostFlow.Edge reverseEdge;
public Edge(int from, int to, long cost, long cap) {
this.from = from;
this.to = to;
this.cost = cost;
this.cap = cap;
}
public long res() {
return cap - flow;
}
long reducedCost() {
// 残余ネットワークで、常に簡約費用非負を保つ。
// 初期状態ではポテンシャル0だが、負辺を流しきっているのでok。
// cost - potential[to] + potential[from] >= 0
// potential[to] + cost >= potential[to]
// なのである固定した頂点からの距離をpotentialとすると非負になる。
return cost - (potential[to] - potential[from]);
}
void addFlow(long add) {
flow += add;
reverseEdge.flow -= add;
if (flow > cap) {
throw new java.lang.AssertionError();
}
if (reverseEdge.flow > reverseEdge.cap) {
throw new java.lang.AssertionError();
}
excess[from] -= add;
excess[to] += add;
}
@java.lang.Override
public java.lang.String toString() {
return (((((((("from " + from) + " to ") + to) + " : flow=") + flow) + ", cap=") + cap) + ", cost=") + cost;
}
}
public void addEdge(int from, int to, long cost, long cap) {
MinimumCostFlow.Edge e = new MinimumCostFlow.Edge(from, to, cost, cap);
MinimumCostFlow.Edge ie = new MinimumCostFlow.Edge(to, from, -cost, 0);
e.reverseEdge = ie;
ie.reverseEdge = e;
g[from].add(e);
ig[to].add(ie);
}
/**
* 流量が固定されている辺を追加する
*/
public void addFixedFlowEdge(int from, int to, long cost, long flow) {
// https://atcoder.jp/contests/abc231/submissions/73435140
addExcess(from, -flow);
addExcess(to, flow);
base += flow * cost;
}
/**
* supply>0の場合湧き出し、supply<0の場合吸い込み。
* https://atcoder.jp/contests/abc374/submissions/71941544
*
* @param v
* @param supply
*/
public void addExcess(int v, long supply) {
excess[v] += supply;
}
/**
* 始点 {@code s} から終点 {@code t} へ最大容量 {@code cap} 以下のフローを流すときの最小費用を求める。
* 逆方向の容量 {@code cap}、費用 0 の辺 {@code t -> s} を追加し、最小費用循環流に帰着して計算する。
* 実行可能流が存在しない場合は {@code null} を返す。
*
* 計算量: 流量を F として O(F(N + M) log(N + M))
*
* @param s
* 始点 (0 <= s < N)
* @param t
* 終点 (0 <= t < N)
* @param cap
* 流すフローの最大容量上限
* @return 最小費用。実行可能流が存在しない場合は null
*/
public java.lang.Long minCostFlowAtMost(int s, int t, long cap) {
addEdge(t, s, 0, cap);
return minCostCirculation();
}
/**
* 最小費用循環流を求める。
* 存在しなければnullを返す。
* 流量をFとしてO(F(N+M)log(N+M))
*
* @param flow
*/
public java.lang.Long minCostCirculation() {
// https://atcoder.jp/contests/abc407/submissions/71000667
// https://atcoder.jp/contests/practice2/submissions/71006911
for (var edges : g) {
for (var edge : edges) {
if (edge.reducedCost() < 0) {
edge.addFlow(edge.cap);
}
}
}
while (ArrayUtils.max(excess) > 0) {
int src = ArrayUtils.argMax(excess);
updateDistance(src);
int dst = 0;
while ((dst < N) && ((d[dst] == INF) || (excess[dst] >= 0))) {
++dst;
}
if (dst == N) {
return null;
}
long addFlow = java.lang.Math.min(excess[src], -excess[dst]);
{
int cur = dst;
while (cur != src) {
addFlow = java.lang.Math.min(addFlow, incommingShortestPathEdge[cur].res());
cur = incommingShortestPathEdge[cur].from;
}
}
{
int cur = dst;
while (cur != src) {
incommingShortestPathEdge[cur].addFlow(addFlow);
cur = incommingShortestPathEdge[cur].from;
}
}
}
long ret = 0;
for (var edges : g) {
for (var edge : edges) {
ret += edge.flow * edge.cost;
}
}
return ret + base;
}
void updateDistance(int src) {
java.util.Arrays.fill(d, INF);
java.util.Arrays.fill(incommingShortestPathEdge, null);
d[src] = 0;
record State(int v, long d) implements java.lang.Comparable<State> {
@java.lang.Override
public int compareTo(State o) {
return java.lang.Long.compare(this.d, o.d);
}
}
java.util.PriorityQueue<State> pq = new java.util.PriorityQueue<>();
pq.add(new State(src, 0));
while (!pq.isEmpty()) {
State state = pq.poll();
if (state.d > d[state.v]) {
continue;
}
for (MinimumCostFlow.Edge e : g[state.v]) {
if (e.res() == 0) {
continue;
}
if (d[e.to] > (state.d + e.reducedCost())) {
d[e.to] = state.d + e.reducedCost();
pq.add(new State(e.to, d[e.to]));
incommingShortestPathEdge[e.to] = e;
}
}
for (MinimumCostFlow.Edge e : ig[state.v]) {
if (e.res() == 0) {
continue;
}
if (d[e.to] > (state.d + e.reducedCost())) {
d[e.to] = state.d + e.reducedCost();
pq.add(new State(e.to, d[e.to]));
incommingShortestPathEdge[e.to] = e;
}
}
}
for (int i = 0; i < N; ++i) {
if (d[i] != INF) {
potential[i] += d[i];
}
}
}
}
interface MonoidStrategy<Monoid> {
Monoid identity();
Monoid mul(Monoid a, Monoid b);
default Monoid pow(Monoid a, long n) {
if (n < 0) {
throw new java.lang.AssertionError();
}
Monoid ret = identity();
while (n != 0) {
if ((n % 2) == 1) {
ret = mul(ret, a);
}
a = mul(a, a);
n /= 2;
}
return ret;
}
/**
* Solve min_n a^n = t (0 <= n <= maxSearch).
*/
default long discreteLog(Monoid a, Monoid t, long maxSearch) {
return DiscreteLogarithm.discreteLog(a, identity(), t, this::mul, this::mul, maxSearch);
}
}
class MyPrintWriter extends java.io.PrintWriter {
private static MyPrintWriter instance = null;
private MyPrintWriter() {
super(java.lang.System.out);
}
public static MyPrintWriter getInstance() {
if (MyPrintWriter.instance == null) {
MyPrintWriter.instance = new MyPrintWriter();
}
return MyPrintWriter.instance;
}
public MyPrintWriter(java.io.PrintStream out) {
super(out);
}
public void println(char[][] a) {
for (int i = 0; i < a.length; i++) {
println(a[i]);
}
}
}
class OpenHashSet<Key> implements java.lang.Iterable<Key> {
private static final int defaultCapacity = 16;
private int size = 0;
private Key[] keys;
private boolean[] deleted;
private int mask = OpenHashSet.defaultCapacity - 1;
private static final double defaultLoadFactor = 0.75;
private Hash.Strategy<Key> strategy;
@java.lang.SuppressWarnings("unchecked")
public OpenHashSet() {
this(Hash.defaultStrategy());
}
@java.lang.SuppressWarnings("unchecked")
public OpenHashSet(Hash.Strategy<Key> strategy) {
keys = ((Key[]) (new java.lang.Object[OpenHashSet.defaultCapacity]));
deleted = new boolean[OpenHashSet.defaultCapacity];
this.strategy = strategy;
}
@java.lang.SuppressWarnings("unchecked")
public OpenHashSet(Hash.Strategy<Key> strategy, int initialCapacity) {
int capacity = java.lang.Integer.highestOneBit(initialCapacity) * 2;
this.mask = capacity - 1;
keys = ((Key[]) (new java.lang.Object[capacity]));
deleted = new boolean[capacity];
this.strategy = strategy;
}
private int hash(Key key) {
return strategy.hashCode(key) & mask;
}
void resize(int newCapacity) {
var oldKeys = keys;
keys = ((Key[]) (new java.lang.Object[newCapacity]));
deleted = new boolean[newCapacity];
mask = newCapacity - 1;
size = 0;
for (int i = 0; i < oldKeys.length; i++) {
if (oldKeys[i] != null) {
add(oldKeys[i]);
}
}
}
public void add(Key key) {
if (key == null) {
throw new java.lang.AssertionError();
}
if ((size + 1) > (keys.length * OpenHashSet.defaultLoadFactor)) {
resize(keys.length * 2);
}
int start = hash(key);
int i = start;
int firstDeleted = -1;
do {
if (keys[i] == null) {
if (!deleted[i]) {
int target = (firstDeleted != (-1)) ? firstDeleted : i;
keys[target] = key;
deleted[target] = false;
++size;
return;
} else if (firstDeleted == (-1)) {
firstDeleted = i;
}
} else if (strategy.equals(keys[i], key)) {
return;
}
i = (i + 1) & mask;
} while (i != start );
if (firstDeleted != (-1)) {
keys[firstDeleted] = key;
deleted[firstDeleted] = false;
++size;
return;
}
throw new java.lang.AssertionError();
}
public boolean contains(Key key) {
if (key == null) {
return false;
}
int start = hash(key);
int i = start;
do {
if ((keys[i] == null) && (!deleted[i])) {
return false;
}
if ((keys[i] != null) && strategy.equals(keys[i], key)) {
return true;
}
i = (i + 1) & mask;
} while (i != start );
return false;
}
public int size() {
return size;
}
@java.lang.Override
public java.util.Iterator<Key> iterator() {
return new java.util.Iterator<>() {
int id = 0;
@java.lang.Override
public boolean hasNext() {
while (id < keys.length) {
if ((keys[id] != null) && (!deleted[id])) {
return true;
}
++id;
}
return false;
}
@java.lang.Override
public Key next() {
if (!hasNext()) {
throw new java.util.NoSuchElementException();
}
return keys[id++];
}
};
}
/**
* このセットと指定されたオブジェクトが等価であるか検証します。
*
* @param o
* 比較対象のオブジェクト
* @return 等価であれば true, そうでなければ false
O(N)
// 未テスト
*/
@java.lang.Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (!(o instanceof OpenHashSet)) {
return false;
}
OpenHashSet<?> other = ((OpenHashSet<?>) (o));
if (this.size() != other.size()) {
return false;
}
for (int i = 0; i < keys.length; i++) {
if ((keys[i] != null) && (!deleted[i])) {
@java.lang.SuppressWarnings("unchecked")
boolean contains = ((OpenHashSet<java.lang.Object>) (other)).contains(keys[i]);
if (!contains) {
return false;
}
}
}
return true;
}
/**
* このセットのハッシュコード値を返します。
*
* @return ハッシュコード値
O(N)
// 未テスト
*/
@java.lang.Override
public int hashCode() {
int h = 0;
for (int i = 0; i < keys.length; i++) {
if ((keys[i] != null) && (!deleted[i])) {
h += strategy.hashCode(keys[i]);
}
}
return h;
}
}
class Permutation {
public static long inversion(int[] a) {
int n = a.length;
SegTree<java.lang.Long> tree = new SegTree<java.lang.Long>(n, java.lang.Long::sum, 0L);
long ans = 0;
for (int i = 0; i < a.length; ++i) {
ans += tree.fold(a[i] + 1, n);
tree.set(a[i], 1L);
}
return ans;
}
}
/**
* *
*
* @param <T>
* 指定されなければ op は null を単位元として扱う。
* op は、単位元の掛け算を実装する必要はない。
*/
class SegTree<T> {
int n;// 2冪
int inputN;
public T[] v;
private T identity = null;
java.util.function.BinaryOperator<T> op;
public SegTree(int n_, java.util.function.BinaryOperator<T> op) {
this.inputN = n_;
n = java.lang.Integer.highestOneBit(n_) << 1;
v = ((T[]) (new java.lang.Object[2 * n]));
for (int i = 0; i < v.length; ++i) {
v[i] = identity;
}
this.op = op;
}
public SegTree(int n, java.util.function.BinaryOperator<T> op, T identiy) {
this.n = java.lang.Integer.highestOneBit(n) << 1;
this.inputN = n;
v = ((T[]) (new java.lang.Object[2 * this.n]));
this.identity = identiy;
for (int i = 0; i < v.length; ++i) {
v[i] = identity;
}
this.op = op;
}
/**
* モノイド戦略 {@code strategy} を用いて長さ {@code n} のセグメント木を構築する。
*
* <p>計算量: O(n)</p>
* // 未テスト
*
* @param n
* 要素数
* @param strategy
* モノイドの演算および単位元を定義する Strategy
*/
public SegTree(int n, MonoidStrategy<T> strategy) {
this(n, strategy::mul, strategy.identity());
}
/**
* モノイド戦略 {@code strategy} と初期配列 {@code a} を用いてセグメント木を構築する。
*
* <p>計算量: O(n)</p>
* // 未テスト
*
* @param a
* 初期要素配列
* @param strategy
* モノイドの演算および単位元を定義する Strategy
*/
public SegTree(T[] a, MonoidStrategy<T> strategy) {
this(a.length, strategy);
build(a);
}
/**
* 二項演算 {@code op}、単位元 {@code identity}、初期配列 {@code a} を用いてセグメント木を構築する。
*
* <p>計算量: O(n)</p>
* // 未テスト
*
* @param a
* 初期要素配列
* @param op
* 2項演算
* @param identity
* 単位元
*/
public SegTree(T[] a, java.util.function.BinaryOperator<T> op, T identity) {
this(a.length, op, identity);
build(a);
}
public void build(T[] a) {
for (int i = 0; i < a.length; i++) {
v[id(i, i + 1)] = a[i];
}
for (int i = n - 1; i >= 1; i--) {
v[i] = op(v[2 * i], v[(2 * i) + 1]);
}
}
public void set(int k, T t) {
k = id(k, k + 1);
v[k] = t;
while (k != id(0, n)) {
k /= 2;
v[k] = op(v[2 * k], v[(2 * k) + 1]);
}
}
// [a2^k, (a+1)2^k)
int id(int a, int b) {
int w = b - a;
return (n / w) + (a / w);
}
public T fold(int l, int r) {
r = java.lang.Math.min(r, n);
l = java.lang.Math.max(l, 0);
if ((r - l) <= 0) {
return identity;
}
int ml = l + java.lang.Integer.lowestOneBit(l);
int mr = r - java.lang.Integer.lowestOneBit(r);
if ((l < ml) && (ml <= r)) {
return op(v[id(l, ml)], fold(ml, r));
} else {
return op(fold(l, mr), v[id(mr, r)]);
}
}
T op(T a, T b) {
if (a == identity) {
return b;
}
if (b == identity) {
return a;
}
return op.apply(a, b);
}
@java.lang.Override
public java.lang.String toString() {
java.lang.String ret = "";
for (int w = 1; w <= n; w *= 2) {
for (int i = 0; i < w; ++i) {
ret += (v[i + w] == null ? "id" : v[i + w].toString()) + " ".repeat(n == w ? 1 : ((2 * n) / w) - 1);
}
ret += "\n";
}
return ret;
}
}
// --- Original Code ---
//library:https://github.com/Maruoka842/library_public
//
// import java.io.IOException;
// import java.util.Arrays;
// import java.util.Random;
//
// import library.tools.FastScanner;
// import library.tools.MergeFiles;
// import library.tools.MyPrintWriter;
// import library.util.ArrayUtils;
// import library.util.collections.IntArrayList;
// import library.util.graph.flow.MinimumCostFlow;
// import library.util.seq.Permutation;
//
// public class Main implements Runnable {
//
// public static void main(String[] args) throws IOException {
// // Runtime runtime = Runtime.getRuntime();
// // new Thread(null, new Main(), "MainThreadWithLargeStack", (1024 * 1024) *1024).start();
// new Main().run();
// // long usedMemory = runtime.totalMemory() - runtime.freeMemory();
// // System.err.printf("使用メモリ: %.2f MB%n", usedMemory / 1024.0 / 1024.0);
// MyPrintWriter.getInstance().flush();
// MergeFiles.export();
// }
//
// Random rnd=new Random();
//
// @java.lang.Override
// public void run() {
// FastScanner sc = FastScanner.getInstance();
// MyPrintWriter pw = MyPrintWriter.getInstance();
// int N=sc.nextInt();
// int[]A=sc.nextInts(4*N);
// long startTime=System.nanoTime();
// ArrayUtils.decrementAll(A);
// char[][] S = new char[N][N];
// ArrayUtils.fill(S, '0');
// MinimumCostFlow mf=new MinimumCostFlow(4*N+2);
// for (int i = 0; i < N; i++) {
// mf.addEdge(i, 3*N-1-i, cost(i, A[i], 3*N-1-i, A[3*N-1-i]), 1);
// }
// for (int i = 0; i < N; i++) {
// for (int j = N; j < 4*N; j++) {
// if(2*N <= j && j < 3*N) continue;
// mf.addEdge(i, j, cost(i, A[i], j, A[j]), 1);
// }
// }
// int source=4*N;
// int sink=source+1;
// for (int i = 0; i < N; i++) {
// mf.addFixedFlowEdge(source, i, 0, 1);
// }
// for (int i = N; i < 4*N; i++) {
// mf.addEdge(i, sink, 0, 1);
// }
// mf.minCostFlowAtMost(source, sink, N);
// for (int i = 0; i < N; i++) {
// for(var e : mf.g[i]) {
// if(e.flow > 0) {
// if (N <= e.to && e.to < 2*N) {
// S[e.to-N][i]='2';
// }
// if (3*N <= e.to && e.to < 4*N) {
// S[N-1-(e.to-3*N)][i]='1';
// }
// }
// }
// }
// // pw.println(S);
// long TL=1900L*1000*1000;
// long curScore = eval(A, S);
// for (int T = 0; T < 1000000; T++) {
// if(T%100==0) {
// long dt=System.nanoTime()-startTime;
// if(dt>=TL)break;
// }
// int i = rnd.nextInt(N);
// int j = rnd.nextInt(N);
// int v = rnd.nextInt(3);
// if(S[i][j] - '0' == v) continue;
// char pre = S[i][j];
// S[i][j] = (char)('0' + v);
// long score = eval(A, S);
// if(score > curScore) {
// S[i][j] = pre;
// } else {
// curScore = score;
// }
// }
// pw.println(S);
//
// }
//
// int cost(int i0, int v0, int i1, int v1) {
// int d0=Math.abs(i0 - v1);
// int d1=Math.abs(i1 - v0);
// return d0+d1;
// }
//
// long eval(int[]A, char[][]S) {
// int N=S.length;
// int[]B=new int[4 * N];
// int[]di=new int[] {1, 0, -1, 0};
// int[]dj=new int[] {0, -1, 0, 1};
// for (int t = 0; t < A.length; t++) {
// int dir=t/N;//↓、←、↑、→
// int i, j;
// if (t < N) {
// i = 0;
// j = t;
// } else if (t < 2*N) {
// i = t % N;
// j = N - 1;
// } else if (t < 3*N) {
// i = N - 1;
// j = N - 1 - t % N;
// } else {
// i = N - 1 - t % N;
// j = 0;
// }
// while(true) {
// if (S[i][j] == '1') {
// if (dir == 0) dir = 1;
// else if (dir == 1) dir = 0;
// else if (dir == 2) dir = 3;
// else if (dir == 3) dir = 2;
// } else if (S[i][j] == '2') {
// ////↓、←、↑、→
// if (dir == 0) dir = 3;
// else if (dir == 3) dir = 0;
// else if (dir == 2) dir = 1;
// else if (dir == 1) dir = 2;
// }
// i += di[dir];
// j += dj[dir];
// if (!(0 <= i && i < N && 0 <= j && j < N)) {
// if (i == -1) {
// B[j] = A[t];
// } else if (i == N) {
// B[3*N-1-j] = A[t];
// } else if (j == -1) {
// B[4*N-1-i] = A[t];
// } else if (j == N) {
// B[N+i] = A[t];
// }
// break;
// }
// }
// }
// return Permutation.inversion(B);
// }
//
//
// void tr(Object...objects) {System.out.println(Arrays.deepToString(objects));}
// }
//
//
37zigen