結果

問題 No.5026 Spectrum Router
コンテスト
ユーザー 37zigen
提出日時 2026-11-24 15:58:01
言語 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,912 ms / 2,000 ms
+ 724µs
コード長 30,386 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 4,205 ms
コンパイル使用メモリ 115,228 KB
実行使用メモリ 60,628 KB
スコア 1,468,271
最終ジャッジ日時 2026-11-24 15:59:55
合計ジャッジ時間 106,089 ms
ジャッジサーバーID
(参考情報)
judge6_0 / judge5_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(0);

    @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';
                    }
                }
            }
        }
        long TL = (1900L * 1000) * 1000;
        int[][][] memo = new int[4][N][N];
        var initialResult = eval(A, S, memo);
        long curScore = initialResult.score;
        int[] B = initialResult.B;
        int[] ts = new int[4];
        int[] oldB = new int[4];
        double startTmp = 30;
        double endTmp = 1;
        double progress = 0;
        double curTmp = startTmp;
        for (int T = 0; T < 1000000; T++) {
            if ((T & 127) == 0) {
                long dt = java.lang.System.nanoTime() - startTime;
                if (dt >= TL) {
                    java.lang.System.err.println("iteration" + T);
                    break;
                }
                progress = (1.0 * dt) / TL;
                curTmp = startTmp * java.lang.Math.pow(endTmp / startTmp, progress);
            }
            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];
            int k = 0;
            for (int d = 0; d < 4; d++) {
                int t = memo[d][i][j];
                if (t == (-1)) {
                    continue;
                }
                boolean dup = false;
                for (int x = 0; x < k; x++) {
                    if (ts[x] == t) {
                        dup = true;
                    }
                }
                if (!dup) {
                    ts[k++] = t;
                }
            }
            for (int x = 0; x < k; x++) {
                oldB[x] = B[ts[x]];
            }
            for (int x = 0; x < k; x++) {
                trace(S, memo, N, ts[x], -1);
            }
            S[i][j] = ((char) ('0' + v));
            for (int x = 0; x < k; x++) {
                B[trace(S, memo, N, ts[x], ts[x])] = A[ts[x]];
            }
            long score = Permutation.inversion(B);
            boolean update = (score > curScore) || (rnd.nextDouble() < java.lang.Math.exp((score - curScore) / curTmp));
            if (update) {
                for (int x = 0; x < k; x++) {
                    trace(S, memo, N, ts[x], -1);
                }
                S[i][j] = pre;
                for (int x = 0; x < k; x++) {
                    trace(S, memo, N, ts[x], ts[x]);
                }
                for (int x = 0; x < k; x++) {
                    B[ts[x]] = oldB[x];
                }
            } 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;
    }

    Main.Result eval(int[] A, char[][] S, int[][][] memo) {
        ArrayUtils.fill(memo, -1);
        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;
                    }
                }
                memo[dir][i][j] = t;
                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 new Main.Result(B, ((int) (Permutation.inversion(B))));
    }

    record Result(int[] B, int score) {}

    static final int[] DI = new int[]{ 1, 0, -1, 0 };

    static final int[] DJ = new int[]{ 0, -1, 0, 1 };

    // t の光線をなぞり、通過した (dir,i,j) に memo=mark を書く。出口の B 添字を返す。
    int trace(char[][] S, int[][][] memo, int N, int t, int mark) {
        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) {
            char c = S[i][j];
            if (c == '1') {
                dir ^= 1;
            }// 0<->3, 1<->2
             else if (c == '2') {
                dir = 3 - dir;
            }// 0<->3, 1<->2

            memo[dir][i][j] = mark;
            i += Main.DI[dir];
            j += Main.DJ[dir];
            if (i < 0) {
                return j;
            }
            if (i >= N) {
                return ((3 * N) - 1) - j;
            }
            if (j < 0) {
                return ((4 * N) - 1) - i;
            }
            if (j >= N) {
                return N + i;
            }
        } 
    }
}

class ArrayUtils {
    public static void decrementAll(int[] a) {
        for (int i = 0; i < a.length; i++) {
            a[i]--;
        }
    }

    public static void fill(int[] a, int v) {
        java.util.Arrays.fill(a, v);
    }

    public static void fill(int[][] a, int v) {
        ArrayUtils2D.fill(a, v);
    }

    public static void fill(int[][][] a, int v) {
        for (int i = 0; i < a.length; ++i) {
            ArrayUtils.fill(a[i], v);
        }
    }

    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(int[][] a, int v) {
        for (int i = 0; i < a.length; ++i) {
            ArrayUtils.fill(a[i], v);
        }
    }

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

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

/**
 * 流量を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];
            }
        }
    }
}

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 Permutation {
    public static long inversion(int[] a) {
        int n = a.length;
        PopcountBIT tree = new PopcountBIT(n);
        long ans = 0;
        for (int i = 0; i < a.length; ++i) {
            ans += i - tree.sum(a[i]);
            tree.set(a[i], true);
        }
        return ans;
    }
}

/**
 * 1 列に対する Binary Indexed Tree (popcount 版)。
 *
 * 64 要素を 1 ワード(long)にまとめ、ワード内は Long.bitCount で O(1) に処理し、
 * ワード単位の個数だけを Fenwick tree で管理する。
 * よって Fenwick の大きさは n/64 となり、各操作は O(log n - log 64)。
 * メモリも n/64 個の long + n/64 個の int で済む。
 */
class PopcountBIT {
    private final int n;

    private final int words;// ワード数


    private final long[] bits;// 0-indexed のビット列


    private final int[] tree;// Fenwick (1-indexed): ワード j は位置 j+1


    private int total;

    // 全体の 1 の個数
    /**
     * 全て 0 で初期化。
     */
    public PopcountBIT(int n) {
        this.n = n;
        this.words = (n >>> 6) + 1;// 番兵として 1 ワード余分に確保 (sum(n) の境界処理を不要にする)

        this.bits = new long[words];
        this.tree = new int[words + 1];
    }

    /**
     * boolean 配列から O(n/64) で構築。
     */
    public PopcountBIT(boolean[] a) {
        this(a.length);
        for (int i = 0; i < n; i++) {
            if (a[i]) {
                bits[i >>> 6] |= 1L << (i & 63);
            }
        }
        for (int j = 0; j < words; j++) {
            int c = java.lang.Long.bitCount(bits[j]);
            total += c;
            tree[j + 1] += c;
            int p = (j + 1) + ((j + 1) & (-(j + 1)));
            if (p <= words) {
                tree[p] += tree[j + 1];
            }
        }
    }

    /**
     * a[i] を返す。O(1)
     */
    public boolean get(int i) {
        return ((bits[i >>> 6] >>> (i & 63)) & 1L) != 0;
    }

    /**
     * a[i] = v。変化があった場合のみ Fenwick を更新。O(log n - log 64)
     */
    public void set(int i, boolean v) {
        if (get(i) == v) {
            return;
        }
        flip(i);
    }

    /**
     * a[i] を反転。O(log n - log 64)
     */
    public void flip(int i) {
        int w = i >>> 6;
        long mask = 1L << (i & 63);
        int d = ((bits[w] & mask) == 0) ? 1 : -1;
        bits[w] ^= mask;
        total += d;
        for (int x = w + 1; x <= words; x += x & (-x)) {
            tree[x] += d;
        }
    }

    /**
     * [0, r) の 1 の個数。O(log n - log 64)
     */
    public int sum(int r) {
        int w = r >>> 6;
        int s = java.lang.Long.bitCount(bits[w] & ((1L << (r & 63)) - 1));// 端数ワード (r&63==0 なら 0)

        for (int x = w; x > 0; x -= x & (-x)) {
            s += tree[x];
        }// ワード [0, w)

        return s;
    }
}


// --- 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(0);
// 
//     @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';
// 					}
// 				}
// 			}
// 		}
//         //iteration936064
//         long TL=1900L*1000*10000;
//         int[][][]memo=new int[4][N][N];
//         var initialResult = eval(A, S, memo);
//         long curScore = initialResult.score;
//         int[]B = initialResult.B;
//         int[] ts = new int[4];
//         int[] oldB = new int[4];
//         double startTmp=30;
//         double endTmp=1;
//         double progress=0;
//         double curTmp=startTmp;
//         for (int T = 0; T < 1000000; T++) {
// 			if((T&127)==0) {
// 				long dt=System.nanoTime()-startTime;
// 				if(dt>=TL) {
// 				System.err.println("iteration"+T);
// 					break;
// 				}
// 				progress=1.*dt/TL;
// 				curTmp=startTmp*Math.pow(endTmp / startTmp , progress);
// 			}
// 			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];
// 			
// 			int k = 0;
// 			for (int d = 0; d < 4; d++) {
// 			    int t = memo[d][i][j];
// 			    if (t == -1) continue;
// 			    boolean dup = false;
// 			    for (int x = 0; x < k; x++) if (ts[x] == t) dup = true;
// 			    if (!dup) ts[k++] = t;
// 			}
// 			for (int x = 0; x < k; x++) oldB[x] = B[ts[x]];
// 
// 			for (int x = 0; x < k; x++) trace(S, memo, N, ts[x], -1);
// 			S[i][j] = (char) ('0' + v);
// 			for (int x = 0; x < k; x++) B[trace(S, memo, N, ts[x], ts[x])] = A[ts[x]];
// 
// 			long score = Permutation.inversion(B);
// 			boolean update=score > curScore || rnd.nextDouble() < Math.exp((score - curScore) / curTmp);
// 			if (update) {
// 			    for (int x = 0; x < k; x++) trace(S, memo, N, ts[x], -1);
// 			    S[i][j] = pre;
// 			    for (int x = 0; x < k; x++) trace(S, memo, N, ts[x], ts[x]);
// 			    for (int x = 0; x < k; x++) B[ts[x]] = oldB[x];
// 			} 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;
//     }
//     
//     
//     Result eval(int[]A, char[][]S, int[][][] memo) {
//     	ArrayUtils.fill(memo, -1);
//     	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;
// 				}
// 				memo[dir][i][j]=t;
// 				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 new Result(B, (int)Permutation.inversion(B));
//     }
//     
//     record Result(int[]B, int score) {};
//     
//     static final int[] DI = {1, 0, -1, 0};
//     static final int[] DJ = {0, -1, 0, 1};
// 
//     // t の光線をなぞり、通過した (dir,i,j) に memo=mark を書く。出口の B 添字を返す。
//     int trace(char[][] S, int[][][] memo, int N, int t, int mark) {
//         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) {
//             char c = S[i][j];
//             if (c == '1') dir ^= 1;          // 0<->1, 2<->3
//             else if (c == '2') dir = 3 - dir; // 0<->3, 1<->2
//             memo[dir][i][j] = mark;
//             i += DI[dir];
//             j += DJ[dir];
//             if (i < 0)  return j;
//             if (i >= N) return 3 * N - 1 - j;
//             if (j < 0)  return 4 * N - 1 - i;
//             if (j >= N) return N + i;
//         }
//     }
//     
//     
//     void tr(Object...objects) {System.out.println(Arrays.deepToString(objects));}
// }
// 
// 
0