๋ฐฑ์ค€/C++

[๋ฐฑ์ค€/C++] 20040๋ฒˆ ์‚ฌ์ดํด ๊ฒŒ์ž„

yulee_to 2022. 11. 3. 21:48

๋ฐฑ์ค€


๐Ÿค”๋ฌธ์ œ ์ดํ•ด

์„ ๋ถ„์„ ๊ธ‹๋‹ค๊ฐ€ ์‚ฌ์ดํด์ด ๋ฐœ์ƒํ•˜๋Š” ์ง€์ ์„ ์ฐพ๋Š” ๋ฌธ์ œ์ด๋‹ค. ์ ์˜ ์œ„์น˜๋ฅผ ์ •ํ™•ํžˆ ๋ชฐ๋ผ๋„ ์„ ๋ถ„์œผ๋กœ ์ด์–ด์ ธ์žˆ๋Š” ๊ฒฝ์šฐ๋ฅผ ์ฐพ์œผ๋ฉด ๋œ๋‹ค.


๐Ÿ”ฅํ’€์ด๐Ÿ”ฅ

Find-Union ๋ฌธ์ œ๋กœ ๋‘ ์ ์„ ์ด์–ด์ค„ ๋•Œ๋งˆ๋‹ค ๊ทธ ์ ๋“ค์˜ ์ง‘ํ•ฉ์˜ ๋ฒˆํ˜ธ๋ฅผ ๊ฐฑ์‹ ํ•ด์ค€๋‹ค. 

๊ทธ๋Ÿฌ๋‹ค๊ฐ€ ์–ด๋–ค ๋‘ ์ ์„ ์ด์„ ๋•Œ ํ•œ ์ ์˜ ์ง‘ํ•ฉ๊ณผ ๋‹ค๋ฅธ ํ•œ ์ ์˜ ์ง‘ํ•ฉ์˜ ๋ฒˆํ˜ธ๊ฐ€ ๊ฐ™๋‹ค๋Š” ๊ฒƒ์€ ์ด๋ฏธ ์–ด๋– ํ•œ ๊ฒฝ๋กœ๋กœ ์—ฐ๊ฒฐ๋˜์–ด ์žˆ๋Š” ์ƒํƒœ์—์„œ ๋˜ ์„ ๋ถ„์„ ๊ทธ์–ด์ฃผ๋Š” ๊ฒƒ ์ฆ‰, ์‚ฌ์ดํด์ด ์ƒ๊ธฐ๋Š” ๊ฒƒ์ด๋ฏ€๋กœ ๊ทธ ๋•Œ์˜ ์ฐจ๋ก€ ๋ฒˆํ˜ธ๋ฅผ ans ๋ณ€์ˆ˜์— ์ €์žฅํ•ด๋‘”๋‹ค. 

m๋ฒˆ๊นŒ์ง€์˜ ์ฐจ๋ก€๋Š” ๋ชจ๋‘ ์ž…๋ ฅ๋ฐ›์•„์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— flag๋ฅผ ํ†ตํ•ด ans๋ฅผ ๊ตฌํ•œ ๊ฒฝ์šฐ์—” ๋‘ ์ ์„ ์ž…๋ ฅ๋ฐ›๊ธฐ๋งŒ ํ•˜๊ณ  ์ด์™ธ์˜ ์—ฐ์‚ฐ์€ ํ•˜์ง€ ์•Š๋Š”๋‹ค.

๋งˆ์ง€๋ง‰์œผ๋กœ ans๋ฅผ ์ถœ๋ ฅํ•ด์ฃผ๋ฉด ๋œ๋‹ค.

 


#include <iostream>

using namespace std;

int n, m, x, y;
int par[500002];
int ans;

int Find(int a) {
    if (par[a] == a)
        return a;

    return par[a] = Find(par[a]);
}

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

    cin >> n >> m;
    for (int i = 0; i < n; i++) {
        par[i] = i;
    }
    int flag = 1;
    for (int i = 0; i < m; i++) {
        cin >> x >> y;
        if (flag) {
            int par_x = Find(x);
            int par_y = Find(y);
            if (par_x == par_y) {
                ans = i + 1;
                flag = 0;
            } else {
                par[par_y] = par_x;
            }
        }
    }
    cout << ans;
}
728x90