본문 바로가기
[C++] 알고리즘 교육/19. BFS(기본)

[알고리즘 19.1.3] BFS - 이분그래프 판별

by 안산학생 2019. 8. 12.

문제


이분 그래프란, 아래 그림과 같이 정점을 크게 두 집합으로 나눌 수 있는 그래프를 말한다. 여기서 같은 집합에 속한 정점끼리는 간선이 존재해서는 안된다. 예를 들어, 아래 그래프의 경우 정점을 크게 {1, 4, 5}, {2, 3, 6} 의 두 개의 집합으로 나누게 되면, 같은 집합에 속한 정점 사이에는 간선이 존재하지 않으므로 이분 그래프라고 할 수 있다.

그래프가 입력으로 주어질 때, 이 그래프가 이분그래프인지를 판별하는 프로그램을 작성하시오.

 

입력


첫째 줄에 정점의 개수 N과 간선의 개수 M이 주어진다. ( 1 ≤ N ≤ 1,000, 1 ≤ M ≤ 100,000 ) 둘째 줄부터 간선의 정보가 주어진다. 각 줄은 두 개의 숫자 a, b로 이루어져 있으며, 이는 정점 a와 정점 b가 연결되어 있다는 의미이다. (1 ≤ a, b ≤ N)

 

출력


주어진 그래프가 이분 그래프이면 Yes, 아니면 No를 출력한다.

 

예제 입력

6 5

1 2

2 4

3 4

3 5

4 6

예제 출력

Yes

 

예제 입력

4 5

1 2

1 3

1 4

2 4

3 4

예제 출력

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
62
63
64
65
66
67
68
#include<iostream>
#include<vector>
#include<queue>
 
using namespace std;
 
const int MAX = 100005;
vector <int> arr[MAX];
int check[MAX] = {0,};
int color[MAX] = {0,};
queue <int> q;
 
int n, m;
int flag =0;
 
void BFS(){
  if(q.empty()) return;
  int num = q.front();
  
  //cout<<num<<" ";
  
  check[num] = 1;
  int node_color = color[num];
  q.pop();
  
  
  for(int i=0; i<arr[num].size();i++){
    if(color[arr[num][i]]==node_color){
      flag = 1;
      return;
    }
    if(check[arr[num][i]]==0){
      q.push(arr[num][i]);
      check[arr[num][i]] = 1;
      color[arr[num][i]] = node_color * -1;
    }
  }
  
  if(!q.empty()) BFS();
  
}
 
int main(){
  
  cin>>n>>m;
  
  int tempS, tempE;
  cin>>tempS>>tempE;
  arr[tempS].push_back(tempE);
  arr[tempE].push_back(tempS);
  
  int temp1, temp2;
  for(int i=1; i<m; i++){
    cin>>temp1>>temp2;
    arr[temp1].push_back(temp2);
    arr[temp2].push_back(temp1);
  }
  
  q.push(tempS);
  color[tempS] = 1;
  
  BFS();
  
  if(flag == 1cout<<"No"<<endl;
  else cout<<"Yes"<<endl;
  
  return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

댓글