結果

問題 No.5026 Spectrum Router
コンテスト
ユーザー 37zigen
提出日時 2026-11-23 22:21:12
言語 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  
実行時間 128 ms / 2,000 ms
+ 686µs
コード長 16,085 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 2,808 ms
コンパイル使用メモリ 109,156 KB
実行使用メモリ 49,876 KB
スコア 1,135,447
最終ジャッジ日時 2026-11-23 22:21:25
合計ジャッジ時間 12,266 ms
ジャッジサーバーID
(参考情報)
judge6_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.lang.Override
    public void run() {
        FastScanner sc = FastScanner.getInstance();
        MyPrintWriter pw = MyPrintWriter.getInstance();
        int N = sc.nextInt();
        int[] A = sc.nextInts(4 * N);
        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);
    }

    int cost(int i0, int v0, int i1, int v1) {
        return java.lang.Math.abs(i0 - v1) + java.lang.Math.abs(i1 - v0);
    }
}

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.MergeFiles;
// import library.tools.MyPrintWriter;
// import library.util.ArrayUtils;
// import library.util.collections.IntArrayList;
// import library.util.graph.flow.MinimumCostFlow;
// 
// 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);
//         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);        
//     }
//     
//     int cost(int i0, int v0, int i1, int v1) {
//     	return Math.abs(i0 - v1) + Math.abs(i1 - v0);
//     }
//     
//     
//     void tr(Object...objects) {System.out.println(Arrays.deepToString(objects));}
// }
// 
// 
0