# 3、染色法判定二分图

# AcWing 860. 染色法判定二分图

import java.util.*;
import java.util.concurrent.LinkedTransferQueue;

//ACWing
public class Main {
    public static void main(String[] args) {
        Main main = new Main();
        main.init();
    }

    int n, m;
    int N = 2000010;
    int h[] = new int[N];
    int e[] = new int[N];
    int ne[] = new int[N];
    int idx;

    int color[] = new int[N];

    void insert(int a, int b) {
        e[idx] = b;
        ne[idx] = h[a];
        h[a] = idx++;
    }
    boolean dfs(int start, int c) {
        color[start] = c;
        boolean flag = true;
        for (int i = h[start]; i != -1; i = ne[i]) {
            int j = e[i];
            if (color[j] == -1) {
                flag &= dfs(j, 3 - c);
            } else if (color[j] != 3 - c) {
                return false;
            }
        }
        return flag;
    }

    void init() {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        m = sc.nextInt();
        Arrays.fill(color, -1);
        Arrays.fill(h, -1);
        for (int i = 0; i < m; i++) {
            int a = sc.nextInt(), b = sc.nextInt();
            insert(a, b);
            insert(b, a);
        }
        boolean flag =true;
        for (int i = 1; i <= n; i++) {
            if(color[i]==-1){
                flag &= dfs(i, 1);
                if(flag==false) break;
            }

        }
        if (flag) System.out.println("Yes");
        else System.out.println("No");
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61