結果

問題 No.1320 Two Type Min Cost Cycle
ユーザー tenten
提出日時 2020-12-17 21:03:18
言語 Java
(openjdk 23)
結果
WA  
実行時間 -
コード長 1,588 bytes
コンパイル時間 3,868 ms
コンパイル使用メモリ 79,212 KB
実行使用メモリ 66,372 KB
最終ジャッジ日時 2024-09-21 08:16:08
合計ジャッジ時間 18,249 ms
ジャッジサーバーID
(参考情報)
judge5 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 48 WA * 9
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.*;

public class Main {
    static boolean[][] used;
    static long min = Long.MAX_VALUE;
    static ArrayList<HashMap<Integer, Integer>> graph = new ArrayList<>();
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        boolean isArrow = (sc.nextInt() == 1);
        int n = sc.nextInt();
        int m = sc.nextInt();
        for (int i = 0; i < n; i++) {
            graph.add(new HashMap<>());
        }
        for (int i = 0; i < m; i++) {
            int a = sc.nextInt() - 1;
            int b = sc.nextInt() - 1;
            int c = sc.nextInt();
            graph.get(a).put(b, c);
            if (!isArrow) {
                graph.get(b).put(a, c);
            }
        }
        used = new boolean[n][n];
        long[] costs = new long[n];
        for (int i = 0; i < n; i++) {
            Arrays.fill(costs, 0);
            next(i, i, 1, costs);
        }
        if (min == Long.MAX_VALUE) {
            System.out.println(-1);
        } else {
            System.out.println(min);
        }
    }
    
    static void next(int idx, int from, long x, long[] costs) {
        if (costs[idx] != 0) {
            min = Math.min(min, x - costs[idx]);
            return;
        }
        if (used[from][idx]) {
            return;
        }
        used[from][idx] = true;
        costs[idx] = x;
        for (int y : graph.get(idx).keySet()) {
            if (y == from) {
                continue;
            }
            next(y, idx, x + graph.get(idx).get(y), costs);
        }
        costs[idx] = 0;
    }
}
0