結果

問題 No.1293 2種類の道路
ユーザー tenten
提出日時 2020-11-25 20:05:03
言語 Java
(openjdk 23)
結果
AC  
実行時間 1,363 ms / 2,000 ms
コード長 2,233 bytes
コンパイル時間 4,302 ms
コンパイル使用メモリ 79,552 KB
実行使用メモリ 104,268 KB
最終ジャッジ日時 2024-07-23 19:26:25
合計ジャッジ時間 27,436 ms
ジャッジサーバーID
(参考情報)
judge3 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 22
権限があれば一括ダウンロードができます

ソースコード

diff #
プレゼンテーションモードにする

import java.util.*;
public class Main {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int d = sc.nextInt();
int w = sc.nextInt();
UnionFindTree dUft = new UnionFindTree(n);
UnionFindTree wUft = new UnionFindTree(n);
for (int i = 0; i < d; i++) {
int a = sc.nextInt() - 1;
int b = sc.nextInt() - 1;
dUft.unite(a, b);
}
for (int i = 0; i < w; i++) {
int a = sc.nextInt() - 1;
int b = sc.nextInt() - 1;
wUft.unite(a, b);
}
HashMap<Integer, Integer> dCount = new HashMap<>();
HashMap<Integer, Integer> wCount = new HashMap<>();
HashMap<Integer, HashSet<Integer>> bridge = new HashMap<>();
for (int i = 0; i < n; i++) {
int x = dUft.find(i);
if (!dCount.containsKey(x)) {
dCount.put(x, dUft.counts[x]);
}
int y = wUft.find(i);
if (!wCount.containsKey(y)) {
wCount.put(y, wUft.counts[y]);
}
if (!bridge.containsKey(x)) {
bridge.put(x, new HashSet<>());
}
bridge.get(x).add(y);
}
long ans = 0;
for (Map.Entry<Integer, HashSet<Integer>> entry : bridge.entrySet()) {
long count = 0;
for (int y : entry.getValue()) {
count += wCount.get(y);
}
ans += (count - 1) * dCount.get(entry.getKey());
}
System.out.println(ans);
}
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 (x == parents[x]) {
return x;
} else {
return parents[x] = find(parents[x]);
}
}
public boolean same(int x, int y) {
return find(x) == find(y);
}
public void unite(int x, int y) {
int xx = find(x);
int yy = find(y);
if (xx == yy) {
return;
}
parents[xx] = yy;
counts[yy] += counts[xx];
}
}
}
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
0