๐Ÿ“ฆ20040: cycle_game


[์•Œ๊ณ ๋ฆฌ์ฆ˜ ํ’€์ด] ๊ฐ•๋™๊ทœ
Reviewed by Kade Kang (devkade12@gmail.com)
Reviewed:: 2024-02-20
๋ฌธ์ œ ํ™•์ธํ•˜๊ธฐ

ํ’€์ด

  • ์„ ๋ถ„์„ ๊ทธ๋ฆฌ๋ฉด์„œ ์‚ฌ์ดํด์ด ์ƒ๊ธฐ๋Š” ์‹œ๊ธฐ์˜ ์ฐจ๋ก€๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค.
  • Union Find ๋ฐฉ๋ฒ•์„ ํ†ตํ•ด์„œ ์—ฐ๊ฒฐ์ด ์•ˆ๋˜์–ด ์žˆ๋Š” ๊ฒฝ์šฐ ์—ฐ๊ฒฐ์‹œ์ผœ์ฃผ๊ณ , ์—ฐ๊ฒฐ์ด ๋˜์–ด ์žˆ๋Š” ๊ฒฝ์šฐ์—๋Š” ์‚ฌ์ดํด์ด ๋งŒ๋“ค์–ด์ง„ ๊ฒƒ์ด๊ธฐ ๋•Œ๋ฌธ์— ํ•ด๋‹น ๋ฒˆํ˜ธ๋ฅผ ์ถœ๋ ฅํ•ด์ค€๋‹ค.
#include <iostream>
 
#define endl '\n'
using namespace std;
 
int N, M;
int parent[500001];
int res = 0;
 
void Input(){
    cin >> N >> M;
}
 
int Find(int i){
    if(parent[i]==i) return i;
    else return parent[i] = Find(parent[i]);
}
 
int Union(int i, int j){
    i = Find(i);
    j = Find(j);
    if(i==j) {
        return 1;
    }
    else{
        parent[i] = j;
        return 0;
    }
}
 
void Solution(){
    for(int i=1; i<=N; i++){
        parent[i]=i;
    }
    for(int i=1; i<=M; i++){
        int a, b;
        cin >> a >> b;
        if(Union(a, b)){
            res = i;
            break;
        }
    }
    if(res == 0) cout << 0 << endl;
    else cout << res << endl;
}
 
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
 
    Input();
    Solution();
 
    return 0;
}