結果
| 問題 | No.583 鉄道同好会 | 
| コンテスト | |
| ユーザー |  tenten | 
| 提出日時 | 2020-09-07 16:48:58 | 
| 言語 | Java (openjdk 23) | 
| 結果 | 
                                AC
                                 
                             | 
| 実行時間 | 774 ms / 2,000 ms | 
| コード長 | 1,830 bytes | 
| コンパイル時間 | 3,862 ms | 
| コンパイル使用メモリ | 77,028 KB | 
| 実行使用メモリ | 53,676 KB | 
| 最終ジャッジ日時 | 2024-11-29 10:49:00 | 
| 合計ジャッジ時間 | 9,284 ms | 
| ジャッジサーバーID (参考情報) | judge2 / judge3 | 
(要ログイン)
| ファイルパターン | 結果 | 
|---|---|
| sample | AC * 3 | 
| other | AC * 16 | 
ソースコード
import java.util.*;
public class Main {
	public static void main (String[] args) {
    	Scanner sc = new Scanner(System.in);
    	int n = sc.nextInt();
    	int m = sc.nextInt();
    	int[] counts = new int[n];
    	UnionFindTree uft = new UnionFindTree(n);
    	for (int i = 0; i < m; i++) {
    	    int a = sc.nextInt();
    	    int b = sc.nextInt();
    	    uft.unite(a, b);
    	    counts[a]++;
    	    counts[b]++;
    	}
   	    int count = 0;
    	for (int x : counts) {
    	    count += x % 2;
    	}
    	boolean flag = (count <= 2 && uft.isOne());
    	if (flag) {
    	    System.out.println("YES");
    	} else {
    	    System.out.println("NO");
    	}
    }
    
    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) {
            if (!same(x, y)) {
                counts[find(y)] += counts[find(x)];
                counts[find(x)] = 0;
                parents[find(x)] = find(y);
            }
        }
        
        public boolean isOne() {
            int count = 0;
            for (int i = 0; i < counts.length; i++) {
                if (counts[i] > 1) {
                    count++;
                }
            }
            return count <= 1;
        }
    }
}
            
            
            
        