結果
| 問題 |
No.583 鉄道同好会
|
| コンテスト | |
| ユーザー |
neko_the_shadow
|
| 提出日時 | 2019-05-17 18:23:54 |
| 言語 | Java (openjdk 23) |
| 結果 |
AC
|
| 実行時間 | 997 ms / 2,000 ms |
| コード長 | 2,521 bytes |
| コンパイル時間 | 2,533 ms |
| コンパイル使用メモリ | 91,044 KB |
| 実行使用メモリ | 68,104 KB |
| 最終ジャッジ日時 | 2024-09-17 05:58:52 |
| 合計ジャッジ時間 | 11,266 ms |
|
ジャッジサーバーID (参考情報) |
judge5 / judge6 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 16 |
ソースコード
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
String ans = (isOK()) ? "YES" : "NO";
System.out.println(ans);
}
public static boolean isOK() {
Scanner stdin = new Scanner(System.in);
int n = stdin.nextInt();
int m = stdin.nextInt();
UnionFind uf = new UnionFind(n);
Map<Integer, Integer> counter = new HashMap<>();
for (int i = 0; i < m; i++) {
int a = stdin.nextInt();
int b = stdin.nextInt();
uf.union(a, b);
counter.put(a, counter.getOrDefault(a, 0) + 1);
counter.put(b, counter.getOrDefault(b, 0) + 1);
}
List<Integer> keys = counter.keySet().stream().collect(Collectors.toList());
for (int i = 0; i < keys.size(); i++) {
for (int j = 0; j < keys.size(); j++) {
if (uf.find(keys.get(i)) != uf.find(keys.get(j))) {
return false;
}
}
}
// Wikipedia「一筆書き」より抜粋:
// ある連結グラフが一筆書き可能な場合の必要十分条件は、以下の条件のいずれか一方が成り立つことである(オイラー路参照)。
// すべての頂点の次数(頂点につながっている辺の数)が偶数 →運筆が起点に戻る場合(閉路)
// 次数が奇数である頂点の数が2で、残りの頂点の次数は全て偶数 →運筆が起点に戻らない場合(閉路でない路)
// <<< 奇数の頂点数が0または2 >>>
long odd = counter.values().stream().filter(v -> v % 2 != 0).count();
return odd == 0 || odd == 2;
}
private static class UnionFind {
private int[] parents;
public UnionFind(int n) {
parents = IntStream.range(0, n).toArray();
}
public int find(int x) {
if (parents[x] == x) {
return x;
} else {
parents[x] = find(parents[x]);
return parents[x];
}
}
public void union(int x, int y) {
x = find(x);
y = find(y);
if (x != y) {
parents[y] = x;
}
}
}
}
neko_the_shadow