Algorithm/BOJ

[백준] 1976번 여행 가자

면빈이 2019. 11. 14. 21:22

 

[적용한 알고리즘]

유니온 파인드

 

[아이디어]

유니온 파인드 그대로 적용해주면 된다.

 

[생각의 흐름 / 절차] 

1. 유니온 파인드로 길이 있는 애들을 묶어준다. 

 

2. 원하는 여행 경로에서 i 번째와 i + 1 번째 경로에 길이 있는지만

find 함수를 통해 검사하면 된다.

 

[교훈]

X

 

<코드>

#include <cstdio>
#include <utility>
#include <algorithm>
using namespace std;

int parent[201];

int find(int x) {
    if (parent[x] < 0) return x;
    return parent[x] = find(parent[x]);
}
void merge(int x, int y){
    x = find(x);
    y = find(y);

    if (x == y) return;
    parent[x] = y;
}

int main(){
    fill(parent, parent + 201, -1);
    int n, m;
    scanf("%d %d", &n, &m);

    for (int i = 1; i <= n; i++){
        for (int j = 1; j <= n; j++){
            int a; scanf("%d", &a);
            if (a == 1){
                merge(i, j);
            }
        }
    }

    int plan[1001] = { 0 };
    for (int i = 1; i <= m; i++){
        scanf("%d", &plan[i]);
    }

    bool ans = true;

    for (int i = 1; i <= m - 1; i++){
        if (find(plan[i]) != find(plan[i + 1])){
            ans = false;
            break;
        }
    }

    if (ans) printf("YES\n");
    else printf("NO\n");

    return 0;
}