๐ ๋ฌธ์ ๋งํฌ
https://www.acmicpc.net/problem/1707
๐ค ๋ฌธ์
๊ทธ๋ํ์ ์ ์ ์ ์งํฉ์ ๋๋ก ๋ถํ ํ์ฌ, ๊ฐ ์งํฉ์ ์ํ ์ ์ ๋ผ๋ฆฌ๋ ์๋ก ์ธ์ ํ์ง ์๋๋ก ๋ถํ ํ ์ ์์ ๋, ๊ทธ๋ฌํ ๊ทธ๋ํ๋ฅผ ํน๋ณํ ์ด๋ถ ๊ทธ๋ํ (Bipartite Graph) ๋ผ ๋ถ๋ฅธ๋ค.
๊ทธ๋ํ๊ฐ ์ ๋ ฅ์ผ๋ก ์ฃผ์ด์ก์ ๋, ์ด ๊ทธ๋ํ๊ฐ ์ด๋ถ ๊ทธ๋ํ์ธ์ง ์๋์ง ํ๋ณํ๋ ํ๋ก๊ทธ๋จ์ ์์ฑํ์์ค.
๐ฎ ๋ฌธ์ ํด๊ฒฐ ๋ฐฉ๋ฒ
์ด๋ถ ๊ทธ๋ํ๋ ๋ฌธ์ ์ ๋์ ์๋ ๊ฒ ์ฒ๋ผ ์ ์ ๋ผ๋ฆฌ ์ด์ด์ง ๊ทธ๋ํ๋ฅผ ํ๋์ ์งํฉ์ผ๋ก ๋ณด๊ณ ์๋ก ์ฐ๊ฒฐ๋ ์ ์ ๋ผ๋ฆฌ๋ ๋ค๋ฅธ ๋ ๊ทธ๋ฃน์ผ๋ก ์ํ๊ฒ ํ๋ ๊ทธ๋ํ๋ฅผ ๋งํ๋ค.
๋ฐ๋ผ์, ์ด๋ถ ๊ทธ๋ํ๋ฅผ ํ๋ณํ๋ ๋ฐฉ๋ฒ์ ๋ค์๊ณผ ๊ฐ๋ค.
- ์์น ๋์ง ์์ ๋ชจ๋ ์ ์ ์ ๋ํด BFS๋ฅผ ์งํํ๋ค.
- BFS์ ์์ ์ ์ ์ ์์์ ์์์ผ๋ก ์์น ํ๋ค. → colors[start] = RED(1);
- ์ฐ๊ฒฐ๋ ์ ์ ์ ๋ค๋ฅธ ์์์ผ๋ก ์์น ํ๋ค. → colors[next] = colors[start] * -1;
- ์ฐ๊ฒฐ๋ ์ ์ ์ด ์๋ก ๋์ผํ ์์์ ๊ฐ์ง๋ ๊ฒฝ์ฐ ์ด๋ถ ๊ทธ๋ํ๊ฐ ์๋๋ฏ๋ก false ๋ฐํํ๋ค.
- ๋ชจ๋ ์ ์ ์ด ๊ฐ ๋ ๋ฆฝ๋ ๊ทธ๋ฃน์ ๊ตฌ์ฑํ๋ฉด ์ด๋ถ ๊ทธ๋ํ์ด๋ค.
๋ฐฉ๋ฌธ ์ฒ๋ฆฌ๋ฅผ ์์ ๋ฐฐ์ด๋ก ์ฒดํน์ด ๊ฐ๋ฅํ๋ค.
๐ฉ Java ์ฝ๋
package com.algorithm.Baekjoon;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main_1707_์ด๋ถ_๊ทธ๋ํ {
private static List<List<Integer>> graph;
private static int[] colors;
private static final int RED = 1;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int K = Integer.parseInt(br.readLine());
for(int testCase = 0; testCase < K; testCase++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int V = Integer.parseInt(st.nextToken());
int E = Integer.parseInt(st.nextToken());
graph = new ArrayList<>();
colors = new int[V+1];
// ๊ทธ๋ํ ์ด๊ธฐํ
for(int vertex =0 ; vertex <= V; vertex++) {
graph.add(new ArrayList<>());
}
// ๊ทธ๋ํ ์ฐ๊ฒฐ
for(int edge = 0; edge < E; edge++) {
st = new StringTokenizer(br.readLine());
int from = Integer.parseInt(st.nextToken());
int to = Integer.parseInt(st.nextToken());
graph.get(from).add(to);
graph.get(to).add(from);
}
boolean rst = false;
// 1. ์์น ๋์ง ์์ ๋ชจ๋ ์ ์ ์ ๋ํด์
for(int vertex = 1; vertex <= V; vertex++) {
if(colors[vertex] == 0) {
rst = isBipartiteGraph(vertex, RED);
}
if(!rst) break;
}
if(rst) System.out.println("YES");
else System.out.println("NO");
}
br.close();
}
private static boolean isBipartiteGraph(int start, int color) {
Queue<Integer> queue = new LinkedList<>();
queue.add(start);
// 2. ์์ ์ ์ ์์์ ์์์ผ๋ก ์์น
colors[start] = color;
while(!queue.isEmpty()) {
int cur = queue.poll();
for(int next : graph.get(cur)) {
// 4. ์ธ์ ์ ์ ์์ด ๋์ผํ๋ฉด ์ด๋ถ ๊ทธ๋ํ๊ฐ ์๋
if(colors[cur] == colors[next]) return false;
// 3. ์ธ์ ์ ์ ์์น ์๋ ๊ฒฝ์ฐ ํ์ฌ ์ ์ ๋ฐ๋ ์๊น๋ก ์์น
// ์์ ๋ฐฐ์ด์ ํตํด ๋ฐฉ๋ฌธ ์ฌ๋ถ ํ์ธ ๊ฐ๋ฅ
if(colors[next] == 0) {
colors[next] = colors[cur] * -1;
queue.add(next);
}
}
}
return true;
}
}
'Algorithm > ๊ทธ๋ํ(Graph)' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค, Java] 2623๋ฒ : ์์ ํ๋ก๊ทธ๋จ (0) | 2022.08.09 |
---|---|
[ํ๋ก๊ทธ๋๋จธ์ค, Java] ํฉ์น ํ์ ์๊ธ (0) | 2022.08.09 |
[๋ฐฑ์ค, Java] 1414๋ฒ : ๋ถ์ฐ์ด์๋๊ธฐ (0) | 2022.06.08 |
[๋ฐฑ์ค, Java] 18352๋ฒ : ํน์ ๊ฑฐ๋ฆฌ์ ๋์ ์ฐพ๊ธฐ (0) | 2022.05.13 |