結果

問題 No.5026 Spectrum Router
コンテスト
ユーザー 37zigen
提出日時 2026-11-24 21:46:38
言語 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  
実行時間 100 ms / 2,000 ms
+ 300µs
コード長 29,487 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 2,486 ms
コンパイル使用メモリ 100,480 KB
実行使用メモリ 46,208 KB
スコア 1,236,595
最終ジャッジ日時 2026-11-24 21:46:49
合計ジャッジ時間 10,948 ms
ジャッジサーバーID
(参考情報)
judge1_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.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');
        {
            int source = 2 * N;
            int sink = source + 1;
            MinimumCostFlow mf = new MinimumCostFlow((2 * N) + 2);
            // choice[c][r]: 列 c と行 r を割り当てたときのセルの種類
            char[][] choice = new char[N][N];
            for (int c = 0; c < N; c++) {
                int top = c;
                int bottom = ((3 * N) - 1) - c;
                for (int r = 0; r < N; r++) {
                    int right = N + r;
                    int left = ((4 * N) - 1) - r;
                    int cost0 = cost(top, A[top], bottom, A[bottom]) + cost(left, A[left], right, A[right]);
                    int cost1 = cost(top, A[top], left, A[left]) + cost(bottom, A[bottom], right, A[right]);
                    int cost2 = cost(top, A[top], right, A[right]) + cost(bottom, A[bottom], left, A[left]);
                    int bestCost = cost0;
                    char bestType = '0';
                    if (cost1 < bestCost) {
                        bestCost = cost1;
                        bestType = '1';
                    }
                    if (cost2 < bestCost) {
                        bestCost = cost2;
                        bestType = '2';
                    }
                    choice[c][r] = bestType;
                    mf.addEdge(c, N + r, bestCost, 1);
                }
            }
            for (int c = 0; c < N; c++) {
                mf.addFixedFlowEdge(source, c, 0, 1);
            }
            for (int r = 0; r < N; r++) {
                mf.addEdge(N + r, sink, 0, 1);
            }
            mf.minCostFlowAtMost(source, sink, N);
            for (int c = 0; c < N; c++) {
                for (var e : mf.g[c]) {
                    if (((e.flow <= 0) || (e.to < N)) || (e.to >= (2 * N))) {
                        continue;
                    }
                    int r = e.to - N;
                    S[r][c] = choice[c][r];
                }
            }
        }
        // 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];
        // double startTmp=10;
        // double endTmp=0.1;
        // double progress=0;
        // double curTmp=startTmp;
        // char[][]bestS=S;
        // long bestScore=Integer.MAX_VALUE;
        // for (int T = 0; ; 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(5);
        // if(v>=3)v=0;
        // if(S[i][j] - '0' == v) continue;
        // char pre = S[i][j];
        // 
        // memo[d][i][j] 向き d で出ていった光線の出発点
        // int[]F=new int[4];//F[d]=方向dで出た光の行き先
        // for (int d = 0; d < 4; ++d) {
        // F[(mirror(d, pre-'0') + 2) & 3] = memo[d][i][j];
        // }
        // boolean fast = (F[0] | F[1] | F[2] | F[3]) >= 0
        // && F[0] != F[1] && F[0] != F[2] && F[0] != F[3]
        // && F[1] != F[2] && F[1] != F[3] && F[2] != F[3];
        // if (fast) {
        // int[]nB=B.clone();
        // for (int d = 0; d < 4; d++) {
        // int p = F[mirror(d, v)];
        // if (p == -1) continue;
        // if (F[(d + 2) & 3] == -1) continue;
        // int val = A[F[(d + 2) & 3]];
        // nB[p] = val;
        // }
        // 
        // long score = Permutation.inversion(nB);
        // boolean update=score < curScore || rnd.nextDouble() < Math.exp((curScore -score) / curTmp);
        // if (!update) {
        // } else {
        // curScore = score;
        // B = nB;
        // 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++) {
        // 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]];
        // }
        // }
        // } else {
        // 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;
        // }
        // int[] prevB = B;
        // B = B.clone();
        // 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((curScore - score) / 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]);
        // }
        // B = prevB;            // 参照を戻すだけでよい
        // } else {
        // curScore = score;
        // }
        // }
        // if (T > 150000 && curScore < bestScore) {
        // bestScore = curScore;
        // bestS = ArrayUtils.copy(S);
        // }
        // }
        // pw.println(bestS);
        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;
    }
}

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

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


// --- 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.graph.grid.Grid2D;
// 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');
//          {
//         	   int source = 2 * N;
//         	    int sink = source + 1;
//         	    MinimumCostFlow mf = new MinimumCostFlow(2 * N + 2);
// 
//         	    // choice[c][r]: 列 c と行 r を割り当てたときのセルの種類
//         	    char[][] choice = new char[N][N];
// 
//         	    for (int c = 0; c < N; c++) {
//         	        int top = c;
//         	        int bottom = 3 * N - 1 - c;
// 
//         	        for (int r = 0; r < N; r++) {
//         	            int right = N + r;
//         	            int left = 4 * N - 1 - r;
// 
//         	            int cost0 =
//         	                    cost(top, A[top], bottom, A[bottom])
//         	                    + cost(left, A[left], right, A[right]);
// 
//         	            int cost1 =
//         	                    cost(top, A[top], left, A[left])
//         	                    + cost(bottom, A[bottom], right, A[right]);
// 
//         	            int cost2 =
//         	                    cost(top, A[top], right, A[right])
//         	                    + cost(bottom, A[bottom], left, A[left]);
// 
//         	            int bestCost = cost0;
//         	            char bestType = '0';
// 
//         	            if (cost1 < bestCost) {
//         	                bestCost = cost1;
//         	                bestType = '1';
//         	            }
// 
//         	            if (cost2 < bestCost) {
//         	                bestCost = cost2;
//         	                bestType = '2';
//         	            }
// 
//         	            choice[c][r] = bestType;
//         	            mf.addEdge(c, N + r, bestCost, 1);
//         	        }
//         	    }
// 
//         	    for (int c = 0; c < N; c++) {
//         	        mf.addFixedFlowEdge(source, c, 0, 1);
//         	    }
// 
//         	    for (int r = 0; r < N; r++) {
//         	        mf.addEdge(N + r, sink, 0, 1);
//         	    }
// 
//         	    mf.minCostFlowAtMost(source, sink, N);
// 
//         	    for (int c = 0; c < N; c++) {
//         	        for (var e : mf.g[c]) {
//         	            if (e.flow <= 0 || e.to < N || e.to >= 2 * N) {
//         	                continue;
//         	            }
// 
//         	            int r = e.to - N;
//         	            S[r][c] = choice[c][r];
//         	        }
//         	    }
//          }
// //         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];
// //         double startTmp=10;
// //         double endTmp=0.1;
// //         double progress=0;
// //         double curTmp=startTmp;
// //         char[][]bestS=S;
// //         long bestScore=Integer.MAX_VALUE;
// //         for (int T = 0; ; 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(5);
// // 			if(v>=3)v=0;
// // 			if(S[i][j] - '0' == v) continue;
// // 			char pre = S[i][j];
// // 			
// // 			//memo[d][i][j] 向き d で出ていった光線の出発点
// // 			int[]F=new int[4];//F[d]=方向dで出た光の行き先
// // 			for (int d = 0; d < 4; ++d) {
// // 				F[(mirror(d, pre-'0') + 2) & 3] = memo[d][i][j];
// // 			}
// //            boolean fast = (F[0] | F[1] | F[2] | F[3]) >= 0
// //                    && F[0] != F[1] && F[0] != F[2] && F[0] != F[3]
// //                    && F[1] != F[2] && F[1] != F[3] && F[2] != F[3];
// // 			if (fast) {
// // 				int[]nB=B.clone();
// // 				for (int d = 0; d < 4; d++) {
// // 					int p = F[mirror(d, v)]; 
// // 					if (p == -1) continue;
// // 					if (F[(d + 2) & 3] == -1) continue;
// // 					int val = A[F[(d + 2) & 3]];
// // 					nB[p] = val;
// // 				}
// // 				
// // 	 			long score = Permutation.inversion(nB);
// // 	 			boolean update=score < curScore || rnd.nextDouble() < Math.exp((curScore -score) / curTmp);
// // 	 			if (!update) {
// // 	 			} else {
// // 	 			    curScore = score;
// // 	 			    B = nB;
// // 	 			    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++) {
// // 	 	                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]];
// // 	 	            }
// // 	 			}
// // 			} else {
// // 			    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;
// // 			    }
// // 			    int[] prevB = B;
// // 			    B = B.clone();
// // 			    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((curScore - score) / 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]);
// // 			        }
// // 			        B = prevB;            // 参照を戻すだけでよい
// // 			    } else {
// // 			        curScore = score;
// // 			    }
// // 			}
// // 			if (T > 150000 && curScore < bestScore) {
// // 				bestScore = curScore;
// // 				bestS = ArrayUtils.copy(S);
// // 			}
// // 		}
// //         pw.println(bestS);
//          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;
//      }
//      
//      int mirror(int dir, int type) {
//     	 if(type==0)return dir;
//     	 if(type==1)return 3-dir;
//     	 if(type==2)return dir^1;
//     	 throw new AssertionError();
//      }
//      
//      
//      Result eval(int[]A, char[][]S, int[][][] memo) {
//      	ArrayUtils.fill(memo, -1);
//      	int N=S.length;
//      	int[]B=new int[4 * N];
//      	int[]di=Grid2D.dh;
//      	int[]dj=Grid2D.dw;
//      	for (int t = 0; t < A.length; t++) {
//      		int dir= (4 - t / N) & 3;//↓、→、↑、←
//  			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) {
//  				dir = mirror(dir, S[i][j] - '0');
//  				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 = Grid2D.dh;
//      static final int[] DJ = Grid2D.dw;
//  
//      // t の光線をなぞり、通過した (dir,i,j) に memo=mark を書く。出口の B 添字を返す。
//      int trace(char[][] S, int[][][] memo, int N, int t, int mark) {
//          int dir = (4 - t / N) & 3;
//          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];
//              dir = mirror(dir, c - '0');
//              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