Post

[BaekJoon] 1976번 - 여행 가자 [Java][C++]

[BaekJoon] 1976번 - 여행 가자 [Java][C++]

문제 링크


1. 아이디어


N개의 도시들이 있고 도시간 길이 있는지 여부가 주어졌을 때 여행 계획에 속한 도시들을 모두 방문할 수 있는지 판단하는 문제다. 모든 도시들이 하나의 그래프 안에 존재하면 어떻게든 방문할 수 있으므로 유니온 파인드 알고리즘을 활용해서 도시들을 그룹핑한 후 모두 같은 그룹에 속했는지 판단하는 방식으로 해결했다.


2. 코드


1. 풀이 [Java]

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
import java.io.*;
import java.util.*;

public class Main {

    static int[] p;

    static void make(int n) {
        p = new int[1 + n];
        for (int i = 1; i <= n; i++) {
            p[i] = i;
        }
    }

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

    static void union(int x, int y) {
        p[find(y)] = find(x);
    }

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

        int n = Integer.parseInt(br.readLine());
        int m = Integer.parseInt(br.readLine());

        make(n);
        for (int i = 1; i <= n; i++) {
            st = new StringTokenizer(br.readLine());
            for (int j = 1; j <= n; j++) {
                if (Integer.parseInt(st.nextToken()) == 1) union(i, j);
            }
        }

        st = new StringTokenizer(br.readLine());
        int root = find(Integer.parseInt(st.nextToken()));
        m--;

        while (m-- > 0) {
            if (root != find(Integer.parseInt(st.nextToken()))) {
                System.out.println("NO");
                return;
            }
        }

        System.out.println("YES");
    }
}


2. 풀이 [C++]

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
#include <bits/stdc++.h>
using namespace std;

vector<int> p(201, -1);

int find(int x) {
    if (p[x] < 0) return x;
    return p[x] = find(p[x]);
}

void unite(int x, int y) {
    x = find(x);
    y = find(y);
    if (x != y) p[y] = x;
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    int n, m;
    cin >> n >> m;

    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            int x;
            cin >> x;
            if (x == 1) unite(i, j);
        }
    }

    int x;
    cin >> x;

    int root = find(x);
    m--;

    while (m--) {
        cin >> x;
        if (root != find(x)) {
            cout << "NO";
            return 0;
        }
    }

    cout << "YES";
}

3. 디버깅


없음.


4. 참고


없음.


This post is licensed under CC BY 4.0 by the author.