結果

問題 No.845 最長の切符
ユーザー htensai
提出日時 2020-01-28 10:54:53
言語 Java
(openjdk 23)
結果
AC  
実行時間 2,903 ms / 3,000 ms
コード長 1,671 bytes
コンパイル時間 3,104 ms
コンパイル使用メモリ 80,052 KB
実行使用メモリ 52,460 KB
最終ジャッジ日時 2024-09-15 07:53:16
合計ジャッジ時間 20,209 ms
ジャッジサーバーID
(参考情報)
judge3 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 27
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.*;

public class Main {
    static HashMap<Integer, Integer>[] graph;
    static int max = 0;
    static int[][] dp;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        graph = new HashMap[n];
        for (int i = 0; i < n; i++) {
            graph[i] = new HashMap<>();
        }
        dp = new int[n][(int)(Math.pow(2, n))];
        for (int i = 0; i < m; i++) {
            int a = sc.nextInt() - 1;
            int b = sc.nextInt() - 1;
            int c = sc.nextInt();
            if (!graph[a].containsKey(b) || graph[a].get(b) < c) {
                graph[a].put(b, c);
            }
            if (!graph[b].containsKey(a) || graph[b].get(a) < c) {
                graph[b].put(a, c);
            }
        }
        for (int i = 0; i < n; i++) {
            int[] costs = new int[n];
            Arrays.fill(costs, -1);
            search(i, 0, costs);
        }
       System.out.println(max);
   }
   
   static void search(int idx, int total, int[] costs) {
       if (costs[idx] != -1) {
           return;
       }
       int key = 0;
       for (int i = 0; i < costs.length; i++) {
           key *= 2;
           if (costs[i] != -1) {
               key++;
           }
       }
       if (total != 0 && dp[idx][key] >= total) {
           return;
       }
       dp[idx][key] = total;
       max = Math.max(max, total);
       costs[idx] = total;
       for (Map.Entry<Integer, Integer> entry : graph[idx].entrySet()) {
           search(entry.getKey(), total + entry.getValue(), costs);
       }
       costs[idx] = -1;
   }
}
0