algorithm

λ°±μ€€ 1953

rkawk 2024. 8. 1. 22:38

문제

풀이

κ²°κ΅­ μ΄λΆ„κ·Έλž˜ν”„λ₯Ό λ§Œλ“œλŠ” λ¬Έμ œλ‹€.

 

5
1 3
1 5
2 1 4
1 3
1 2

의 경우λ₯Ό 예둜 λ“€μž.

 

μ‹«μ–΄ν•˜λŠ” 관계λ₯Ό 유ν–₯κ·Έλž˜ν”„λ‘œ 그리면 μ΄λ ‡κ²Œ λ‚˜νƒ€λ‚Ό 수 μžˆλ‹€.

 

μ—¬κΈ°μ„œ 1λ²ˆλ…Έλ“œλΆ€ν„° μ²­νŒ€μ— λ“€μ–΄κ°„λ‹€κ³  κ°€μ •ν•˜μž. κ·Έλ ‡κ²Œ λœλ‹€λ©΄ 1번 λ…Έλ“œλŠ” 3λ²ˆμ„ μ‹«μ–΄ν•˜λ―€λ‘œ 3λ²ˆμ€ 무쑰건 λ°±νŒ€μ— λ“€μ–΄κ°€κ²Œ λœλ‹€.

 

3λ²ˆμ„ κΈ°μ€€μœΌλ‘œ 3λ²ˆλ…Έλ“œλŠ” 4λ²ˆμ„ μ‹«μ–΄ν•˜λ―€λ‘œ 4λ²ˆλ…Έλ“œλŠ” μ²­νŒ€μ— λ“€μ–΄κ°€κ²Œ λœλ‹€.

 

4λ²ˆλ…Έλ“œλŠ” μ‹«μ–΄ν•˜λŠ” λ…Έλ“œκ°€ μ—†μœΌλ―€λ‘œ, λ‹€μ‹œ 2λ²ˆλ…Έλ“œλΆ€ν„° μ²­νŒ€μ— λ„£κ³  μ‹œμž‘ν•˜κ²Œ λœλ‹€λ©΄

 

λ‹€μŒκ³Ό 같은 κ·Έλž˜ν”„κ°€ κ·Έλ €μ§€κ²Œ λœλ‹€.

 

μ‹«μ–΄ν•˜λŠ” μ‚¬λžŒμ΄ ν•˜λ‚˜λ„ μ—†λŠ” κ²½μš°λŠ” μ—†μœΌλ―€λ‘œ, ν•œλͺ…λ§Œ μ‹«μ–΄ν•˜λŠ”μ‚¬λžŒμ΄ ν•œλͺ… μžˆλŠ” κ²½μš°κ°€ νƒμƒ‰μ˜ κΈ°μ€€μ—μ„œ κ°€μž₯ 였래 κ±Έλ¦¬λŠ” κ²½μš°λ‹€.

 

λͺ¨λ“  λ…Έλ“œλ₯Ό ν•œλ²ˆμ”©λ§Œ λ°©λ¬Έν•˜λ©΄ λ˜λ―€λ‘œ O(N)이닀.

 

#include <iostream>
#include <vector>
#include <queue>
using namespace std;
vector<vector<int> > v(101);
int n, vis[101], blue[101], white[101], bans, wans;

int main() {
    cin>>n;
    for(int i=1; i<=n; i++) {
        int a; cin>>a;
        while(a--) {
            int b; cin>>b;
            v[i].push_back(b);
        }
    }
    for(int i=1; i<=n; i++) {
        if(vis[i]) continue;
        vis[i] = 1;
        blue[i] = 1; bans += 1;
        queue<int>q;
        q.push(i);
        while(!q.empty()) {
            int cur = q.front(); q.pop();
            for(auto e : v[cur]) {
                if(vis[e]) continue;
                vis[e] = 1;
                if(blue[cur]) {
                    white[e] = 1;
                    wans += 1;
                }
                if(white[cur]) {
                    blue[e] = 1;
                    bans += 1;
                }
                q.push(e);
            }
        }

    }
    cout<<bans<<'\n';
    for(int i=1; i<=n; i++)
        if(blue[i]) cout<<i<<' ';
    cout<<'\n';
    cout<<wans<<'\n';
    for(int i=1; i<=n; i++)
        if(white[i]) cout<<i<<' ';

}