結果
| 問題 |
No.2200 Weird Shortest Path
|
| ユーザー |
tenten
|
| 提出日時 | 2023-03-30 10:55:09 |
| 言語 | Java (openjdk 23) |
| 結果 |
AC
|
| 実行時間 | 902 ms / 2,000 ms |
| コード長 | 3,129 bytes |
| コンパイル時間 | 2,609 ms |
| コンパイル使用メモリ | 89,768 KB |
| 実行使用メモリ | 68,648 KB |
| 最終ジャッジ日時 | 2024-09-21 22:01:18 |
| 合計ジャッジ時間 | 26,498 ms |
|
ジャッジサーバーID (参考情報) |
judge4 / judge1 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 2 |
| other | AC * 44 |
ソースコード
import java.io.*;
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner();
int n = sc.nextInt();
int m = sc.nextInt();
Bridge[] bridges = new Bridge[m];
for (int i = 0; i < m; i++) {
bridges[i] = new Bridge(sc.nextInt() - 1, sc.nextInt() - 1, sc.nextInt());
}
Arrays.sort(bridges);
UnionFindTree uft = new UnionFindTree(n);
long ans = 0;
for (Bridge x : bridges) {
ans += uft.unite(x);
}
System.out.println(ans);
}
static class Bridge implements Comparable<Bridge> {
int left;
int right;
int value;
public Bridge(int left, int right, int value) {
this.left = left;
this.right = right;
this.value = value;
}
public int compareTo(Bridge another) {
return value - another.value;
}
}
static class UnionFindTree {
int[] parents;
int[] counts;
public UnionFindTree(int size) {
parents = new int[size];
counts = new int[size];
for (int i = 0; i < size; i++) {
parents[i] = i;
counts[i] = 1;
}
}
public int find(int x) {
if (parents[x] != x) {
parents[x] = find(parents[x]);
}
return parents[x];
}
public long unite(Bridge b) {
int x = find(b.left);
int y = find(b.right);
if (x == y) {
return 0;
}
long ans = (long)counts[x] * counts[y] * b.value;
parents[x] = y;
counts[y] += counts[x];
return ans;
}
}
}
class Utilities {
static String arrayToLineString(Object[] arr) {
return Arrays.stream(arr).map(x -> x.toString()).collect(Collectors.joining("\n"));
}
static String arrayToLineString(int[] arr) {
return String.join("\n", Arrays.stream(arr).mapToObj(String::valueOf).toArray(String[]::new));
}
}
class Scanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
StringBuilder sb = new StringBuilder();
public Scanner() throws Exception {
}
public int nextInt() throws Exception {
return Integer.parseInt(next());
}
public long nextLong() throws Exception {
return Long.parseLong(next());
}
public double nextDouble() throws Exception {
return Double.parseDouble(next());
}
public int[] nextIntArray() throws Exception {
return Stream.of(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
}
public String next() throws Exception {
while (!st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
}
tenten