티스토리 뷰

PS

[백준] 6018번 Tea Time

Eastplanet 2022. 5. 13. 15:20

문제 출처: https://www.acmicpc.net/problem/6018

 

6018번: Tea Time

N (1 <= N <= 1000) cows, conveniently numbered 1..N all attend a tea time every day. M (1 <= M <= 2,000) unique pairs of those cows have already met before the first tea time. Pair i of these cows who have met is specified by two differing integers A_i and

www.acmicpc.net

유니온 파인드를 이용하여 같은 집합인지 확인하여 출력한다.

#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>

using namespace std;

int arr[1001];

int find(int n) {
    if (arr[n] < 0)return n;
    else return arr[n] = find(arr[n]);
}

void merge(int a, int b) {
    a = find(a);
    b = find(b);
    if (a == b)return;

    if (arr[a] < arr[b]) {
        arr[a] += arr[b];
        arr[b] = a;
    }
    else {
        arr[b] += arr[a];
        arr[a] = b;
    }
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    int N, K;
    fill(arr, arr + 1001, -1);
    cin >> N >> K;
    int m;
    cin >> m;
    for (int i = 0; i < K; i++) {
        int a, b;
        cin >> a >> b;
        merge(a, b);
    }

    
    for (int i = 1; i <= m; i++) {
        int u, v;
        cin >> u >> v;
        u = find(u);
        v = find(v);

        if (u == v)cout << "Y" << '\n';
        else cout << "N" << '\n';
    }
    
}
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2026/01   »
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
글 보관함