728x90
반응형
BFS + DFS
- 제목
이분 그래프
- 조건
시간 제한 : 2 초
메모리 제한 : 256 MB
- 문제
그래프의 정점의 집합을 둘로 분할하여, 각 집합에 속한 정점끼리는 서로 인접하지 않도록 분할할 수 있을 때, 그러한 그래프를 특별히 이분 그래프 (Bipartite Graph) 라 부른다.
그래프가 입력으로 주어졌을 때, 이 그래프가 이분 그래프인지 아닌지 판별하는 프로그램을 작성하시오.
- 입력
입력은 여러 개의 테스트 케이스로 구성되어 있는데, 첫째 줄에 테스트 케이스의 개수 K가 주어진다. 각 테스트 케이스의 첫째 줄에는 그래프의 정점의 개수 V와 간선의 개수 E가 빈 칸을 사이에 두고 순서대로 주어진다. 각 정점에는 1부터 V까지 차례로 번호가 붙어 있다. 이어서 둘째 줄부터 E개의 줄에 걸쳐 간선에 대한 정보가 주어지는데, 각 줄에 인접한 두 정점의 번호 u, v (u ≠ v)가 빈 칸을 사이에 두고 주어진다.
- 출력
K개의 줄에 걸쳐 입력으로 주어진 그래프가 이분 그래프이면 YES, 아니면 NO를 순서대로 출력한다.
- 제한
2 ≤ K ≤ 5
1 ≤ V ≤ 20,000
1 ≤ E ≤ 200,000
예제 입력1 | 예제 출력1 |
2 3 2 1 3 2 3 4 4 1 2 2 3 3 4 4 2 |
YES NO |
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
#define endl '\n'
#define WHITE 0
#define RED 1
#define BLUE 2
bool visited[20001];
int color[20001];
vector<int> graph[20001];
int N, M;
void init(int vertex){
for(int n = 1 ; n <= vertex ; n++) {
visited[n] = false;
color[n] = WHITE;
graph[n].clear();
// 0 no color ; 1 group1 ; 2 group2
}
}
void BFS(int start){
visited[start] = true;
color[start] = RED;
queue<int> que;
que.push(start);
while(!que.empty()){
int curr = que.front();
int curr_color = color[curr];
que.pop();
for(int n = 0 ; n < graph[curr].size() ; n++){
int next = graph[curr][n];
int next_color = color[next];
if(visited[next]) continue;
if(next_color == 0){
if(curr_color == RED) color[next] = BLUE;
else if(curr_color == BLUE) color[next] = RED;
visited[next] = true;
que.push(next);
}
}
}
}
bool colorCheck(int vertex){
for(int n = 1 ; n <= vertex ; n++){
for(int m = 0 ; m < graph[n].size() ; m++){
if(color[n] == color[graph[n][m]]) return false;
}
}
return true;
}
void show(int vertex){
for(int n = 1; n <= vertex ; n++) {
cout << "root [" << n << "] ";
for(int m = 0 ; m < graph[n].size() ; m++){
cout << graph[n][m] << ' ';
}
cout << endl;
}
cout << endl;
for(int n = 1; n <= vertex ; n++) cout << color[n] << ' ';
cout << endl;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int tc, vertex, edge, from, to;
cin >> tc;
while(tc--){
cin >> vertex >> edge;
init(vertex);
for(int n = 0 ; n < edge ; n++){
cin >> from >> to;
graph[from].push_back(to);
graph[to].push_back(from);
}
for(int n = 1 ; n <= vertex ; n++){
if(!visited[n]) BFS(n);
}
if(colorCheck(vertex)) cout << "YES" << endl;
else cout << "NO" << endl;
//show(vertex);
}
return 0;
}
728x90
반응형
'Problem Solving > BaekJoon' 카테고리의 다른 글
[BOJ/백준] 1068 - 트리 (0) | 2022.08.14 |
---|---|
[BOJ/백준] 5430 - AC (0) | 2022.08.14 |
[BOJ/백준] 17213 - 과일 서리 (0) | 2022.08.11 |
[BOJ/백준] 20149 - 선분 교차 3 (0) | 2022.08.10 |
[BOJ/백준] 17387 - 선분 교차 2 (0) | 2022.08.09 |