본문 바로가기
백준

백준 1976번 : 여행 가자

by Huiyeong 2021. 3. 21.

 문제

www.acmicpc.net/problem/1976

 

1976번: 여행 가자

동혁이는 친구들과 함께 여행을 가려고 한다. 한국에는 도시가 N개 있고 임의의 두 도시 사이에 길이 있을 수도, 없을 수도 있다. 동혁이의 여행 일정이 주어졌을 때, 이 여행 경로가 가능한 것인

www.acmicpc.net

1976 여행 가자

 

 구현 방법

 union-find로 구현해주었습니다.

도시의 수 만큼 root 배열인 parents 배열을 만들어주고 도시 집합을 생성합니다.

연결 정보를 받아와 1이면 union(x, y) 로 집합을 합쳐줍니다.

모든 연결이 끝난 후 여행 계획을 받아와 루트 노드를 찾아 같으면 연결되었으므로 "YES" 출력, 다르면 비연결이므로 "NO"를 출력해줍니다.

 

 구현 코드

package BOJ.Gold;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class B1976_여행가자 {
	static int N, M;
	static int[] parents;
	static void makeSet() {
		for (int i=1;i<=N;i++) {
			parents[i] = -1;
		}
	}
	
	static int findSet(int x) {
		if (parents[x]<0) return x;
		return parents[x] = findSet(parents[x]);
	}
	
	static void union(int a, int b) {
		int aRoot = findSet(a);
		int bRoot = findSet(b);
		if (aRoot==bRoot) return;
		parents[bRoot] = aRoot;
	}
	
	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = null;
		N = Integer.parseInt(br.readLine());
		parents = new int[N+1];
		M = Integer.parseInt(br.readLine());
		makeSet(); // 집합 만들기
		for (int i=1;i<=N;i++) {
			st = new StringTokenizer(br.readLine());
			for (int j=1;j<=N;j++) {
				int to = Integer.parseInt(st.nextToken());
				if (to==1) union(i, j); // 1일 때 연결
			}
		}
		boolean flag = true;
		st = new StringTokenizer(br.readLine());
		List<Integer> list = new ArrayList<>();
		while(st.hasMoreTokens()) {
			list.add(Integer.parseInt(st.nextToken())); // 여행 계획 저장
		}
		for(int i=1;i<list.size();i++) {
			if (findSet(list.get(0))!=findSet(list.get(i))) { // 루트 찾아서 같으면 연결, 다르면 비연결
				flag = false;
				break;
			}
		}
		
		if (flag) System.out.println("YES");
		else System.out.println("NO");
	}
}

 

정답!

'백준' 카테고리의 다른 글

백준 16562번 : 친구비  (0) 2021.03.21
백준 1717번 : 집합의 표현  (0) 2021.03.21
백준 11726번 : 2xn 타일링  (0) 2021.03.21
백준 2193번 : 이친수  (0) 2021.03.21
백준 1743번 : 음식물 피하기  (0) 2021.03.21