結果
問題 |
No.1207 グラフX
|
ユーザー |
![]() |
提出日時 | 2020-12-04 08:48:03 |
言語 | Java (openjdk 23) |
結果 |
TLE
|
実行時間 | - |
コード長 | 2,313 bytes |
コンパイル時間 | 2,888 ms |
コンパイル使用メモリ | 80,184 KB |
実行使用メモリ | 154,880 KB |
最終ジャッジ日時 | 2024-09-14 19:02:41 |
合計ジャッジ時間 | 25,429 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge4 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | -- * 3 |
other | TLE * 6 -- * 40 |
ソースコード
import java.util.*; public class Main { static final int MOD = 1000000007; static ArrayList<HashMap<Integer, Integer>> graph = new ArrayList<>(); static int[] sizes; static int n; static int x; static long sum = 0; public static void main(String[] args) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); int m = sc.nextInt(); x = sc.nextInt(); for (int i = 0; i < n; i++) { graph.add(new HashMap<>()); } UnionFindTree uft = new UnionFindTree(n); for (int i = 0; i < m; i++) { int a = sc.nextInt() - 1; int b = sc.nextInt() - 1; int c = sc.nextInt(); if (!uft.same(a, b)) { uft.unite(a, b); graph.get(a).put(b, c); graph.get(b).put(a, c); } } sizes = new int[n]; getSize(0, 0); System.out.println(sum); } static int getSize(int idx, int parent) { sizes[idx] = 1; for (int y : graph.get(idx).keySet()) { if (y == parent) { continue; } int s = getSize(y, idx); sum += pow(x, graph.get(idx).get(y)) * (n - s) % MOD * s % MOD; sum %= MOD; sizes[idx] += s; } return sizes[idx]; } static long pow(long x, int p) { if (p == 0) { return 1; } else if (p % 2 == 0) { return pow(x * x % MOD, p / 2); } else { return x * pow(x, p - 1) % MOD; } } static class UnionFindTree { int[] parents; public UnionFindTree(int size) { parents = new int[size]; for (int i = 0; i < size; i++) { parents[i] = i; } } public int find(int a) { if (parents[a] == a) { return a; } else { return parents[a] = find(parents[a]); } } public boolean same(int a, int b) { return find(a) == find(b); } public void unite(int a, int b) { if (!same(a, b)) { parents[find(a)] = find(b); } } } }