結果

問題 No.5026 Spectrum Router
コンテスト
ユーザー 37zigen
提出日時 2026-11-23 23:28:07
言語 Java
(openjdk 27.0.1.0.3 + ACL)
コンパイル:
javac -J-Duser.language=en -encoding UTF8 -cp /opt/aclib/ac_library.jar _filename_
実行:
java -ea -Xmx700m -Xss256M -DONLINE_JUDGE=true -cp .:/opt/aclib/ac_library.jar _class_
結果
AC  
実行時間 1,931 ms / 2,000 ms
+ 318µs
コード長 30,165 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 3,110 ms
コンパイル使用メモリ 116,452 KB
実行使用メモリ 67,308 KB
スコア 1,426,611
最終ジャッジ日時 2026-11-23 23:29:53
合計ジャッジ時間 105,764 ms
ジャッジサーバーID
(参考情報)
judge4_0 / judge2_0
純コード判定しない問題か言語
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 50
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

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) {
                // System.err.println("iteration"+T);
                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 {
                // System.err.println("update at T="+T);
                curScore = score;
            }
        }
        pw.println(S);
    }

    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);
    }
}

/**
 * 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);
            }
        };
    }
}

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.JavaToCpp;
// 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();
// 		JavaToCpp.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) {
// //				System.err.println("iteration"+T);
// 				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 {
// //				System.err.println("update at T="+T);
// 				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));}
// }
// 
// 
0