알고리즘/백준

[백준 1707] 이분 그래프 C++

겜도리도리 2021. 10. 26. 23:16
반응형

문제

백준 1707 이분 그래프 C++

 

1707번: 이분 그래프

입력은 여러 개의 테스트 케이스로 구성되어 있는데, 첫째 줄에 테스트 케이스의 개수 K가 주어진다. 각 테스트 케이스의 첫째 줄에는 그래프의 정점의 개수 V와 간선의 개수 E가 빈 칸을 사이에

www.acmicpc.net

풀이

모든 정점을 bfs로 돌면서 색깔을 확인해줍니다.

인근 노드와 색깔이 같다면 이분 그래프가 아니므로 즉시 break 후 Ispipartite를 false로 설정합니다.

소스 코드

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <cstring>
using namespace std;
 
vector<int> v[20001];
bool visited[20001];
bool IsBipartite;
int color[20001];
 
void bfs(int start) {
    // 방문했으면 return
    if (visited[start]) {
        return;
    }
    color[start] = 1;
    visited[start] = true;
    queue<int> q;
    q.push(start);
    while (!q.empty()) {
        int cur = q.front();
        int curcolor = color[cur];
        q.pop();
        for (int i = 0; i < v[cur].size(); i++) {
            int next = v[cur][i];
            int nextcolor = color[next];
            // 색깔 0 인경우 (지정안 된 경우)
            if (nextcolor == 0) {
                // 색깔 지정
                if (curcolor == 1) {
                    color[next] = 2;
                }
                else {
                    color[next] = 1;
                }
            }
            // 색깔이 같은 경우에는 이분그래프가 아님
            else if (nextcolor == curcolor) {
                IsBipartite = false;
                return;
            }
            // 방문하지 않았다면 push
            if (!visited[next]) {
                visited[next] = true;
                q.push(next);
            }
        }
    }
}
 
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
 
    int K;
    cin >> K;
    while (K--) {
        // 초기화
        IsBipartite = true;
        memset(visited, 0sizeof(visited));
        memset(color, 0sizeof(color));
        // 입력
        int V, E;
        cin >> V >> E;
        for (int i = 0; i < E; i++) {
            int a, b;
            cin >> a >> b;
            v[a].push_back(b);
            v[b].push_back(a);
        }
        for (int i = 1; i < V; i++) {
            bfs(i);
        }
        if (IsBipartite) {
            cout << "YES" << '\n';
        }
        else {
            cout << "NO" << '\n';
        }
        for (int i = 1; i <= V; i++) {
            v[i].clear();
        }
    }
    return 0;
}
cs
반응형

'알고리즘 > 백준' 카테고리의 다른 글

[백준 1261] 알고스팟 C++  (0) 2021.10.30
[백준 17144] 미세먼지 안녕! C++  (0) 2021.10.29
[백준 1806] 부분합 C++  (0) 2021.10.25
[백준 3055] 탈출 C++  (0) 2021.10.21
[백준 1197] 최소 스패닝 트리 C++  (0) 2021.10.20