[백준 20040] 사이클 게임 ( 골드 4)

2025. 5. 13. 19:01·Study/Algorithm
728x90

https://www.acmicpc.net/problem/20040

 

유니온 파인드 관련된 문제를 찾아서 진행했다.

두 점을 연결하는 과정을 거치면서 사이클이 완성되면 끝나는 게임이다.

 

두 점을 union하면서 isSameParent 로직으로 확인하면서 cycle이 발생하면 몇 번째 union 에서 발생했는지 출력하면 된다.

* 중요 -> union하면서 parent[] 배열로 부모 점을 계속 변경해주어야 한다. 이때는 둘 중 작은 수로 부모를 변경해야 한다.

union -> 두 점을 연결하고 같은 부모를 바라보게 한다.

find -> 각 점의 부모를 찾는다.

isSameParent -> 부모가 같은지 확인한다.

 

최종 코드

package baekjoon._20040;

import java.io.*;
import java.util.*;

/* https://www.acmicpc.net/problem/20040 */
public class Main {
	static int[] parent;
	static int n, m;
	static boolean isCycle;
	static int answer;

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		n = Integer.parseInt(st.nextToken());
		m = Integer.parseInt(st.nextToken());

		parent = new int[n + 1];
		for (int i = 1; i < n + 1; i++) {
			parent[i] = i;
		}

		for (int i = 0; i < m; i++) {
			st = new StringTokenizer(br.readLine());
			int x = Integer.parseInt(st.nextToken());
			int y = Integer.parseInt(st.nextToken());
			if (!isSameParent(x, y)) {
				union(x, y);
				answer++;
			} else {
				isCycle = true;
				answer++;
				break;
			}

		}
		if (isCycle) {
			System.out.println(answer);
		} else {
			System.out.println(0);
		}

	}

	static void union(int x, int y) {
		x = find(x);
		y = find(y);

		if (x != y) {
			if (x < y)
				parent[y] = x;
			else
				parent[x] = y;
		}

	}

	static int find(int x) {
		if (x == parent[x]) {
			return x;
		}
		return parent[x] = find(parent[x]);

	}

	static boolean isSameParent(int x, int y) {
		x = find(x);
		y = find(y);

		if (x == y) {
			return true;
		} else {
			return false;
		}
	}
}

 

심화문제로는 친구 네트워크 4195(골드 2)를 추천한다.

아래는 4195번 힌트이다!

해당 문제는 숫자가 아닌 이름으로 주어져서 Map 자료구조를 활용해야하고, union할 때 합집합 연산을 추가로 해줘야 한다.

728x90
반응형
저작자표시 비영리 변경금지 (새창열림)

'Study > Algorithm' 카테고리의 다른 글

[백준 20208] 진우의 민트초코우유 (골드 5)  (0) 2025.05.14
[백준 32387] 충전하기 (골드 4)  (0) 2025.05.13
[백준 2638] 치즈 (골드 3)  (0) 2025.05.13
[백준 5525] IOIOI  (1) 2024.09.03
[백준 9465] 스티커  (1) 2024.08.30
'Study/Algorithm' 카테고리의 다른 글
  • [백준 20208] 진우의 민트초코우유 (골드 5)
  • [백준 32387] 충전하기 (골드 4)
  • [백준 2638] 치즈 (골드 3)
  • [백준 5525] IOIOI
pink_salt
pink_salt
유익함을 주는 개발자가 되도록 keep going
  • pink_salt
    KeepGoingForever
    pink_salt
  • 전체
    오늘
    어제
    • 분류 전체보기 (117)
      • Project (7)
      • WEB study (3)
        • WEB(Springboot) (10)
        • Git, GitLab (13)
        • Clean code (1)
        • FrontEnd (3)
      • Study (21)
        • Algorithm (19)
        • 면접 준비 (2)
      • Cloud Computing (2)
        • AWS (2)
      • 프로그래밍 언어 (35)
        • Java (29)
        • Python (0)
        • javascript (6)
      • 운영체제 (0)
        • Linux (0)
      • Database (4)
        • MongoDB (8)
        • SQL (8)
      • 애플리케이션 개발 (1)
        • Android (1)
      • AI (1)
        • Deeplearning (1)
        • machinelearning (0)
      • Daily (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    무료IT교육
    자바
    빅오표기법
    Git
    코드프레소
    SW
    python
    codepresso
    MongoDB
    무료코딩교육
    오블완
    객체지향
    IT교육
    mysql
    티스토리챌린지
    코딩강의
    Query
    git branch
    BFS
    dp
    Java
    spring boot
    개념
    백준
    코딩이러닝
    gitlab
    Database
    언어
    SWEA
    대외활동
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
pink_salt
[백준 20040] 사이클 게임 ( 골드 4)
상단으로

티스토리툴바