[c++] BOJ 1707 :: ์ด๋ถ„ ๊ทธ๋ž˜ํ”„

๋‚œ์ด๋„ : ๊ณจ๋“œ 4

๊ฑธ๋ฆฐ ์‹œ๊ฐ„ : ์˜ค๋ž˜ ๊ฑธ๋ฆผ

 

๋ฌธ์ œ

์ด๋ถ„ ๊ทธ๋ž˜ํ”„ ๋ฌธ์ œ ๋ณด๋Ÿฌ๊ฐ€๊ธฐ

๊ทธ๋ž˜ํ”„์˜ ์ •์ ์˜ ์ง‘ํ•ฉ์„ ๋‘˜๋กœ ๋ถ„ํ• ํ•˜์—ฌ, ๊ฐ ์ง‘ํ•ฉ์— ์†ํ•œ ์ •์ ๋ผ๋ฆฌ๋Š” ์„œ๋กœ ์ธ์ ‘ํ•˜์ง€ ์•Š๋„๋ก ๋ถ„ํ• ํ•  ์ˆ˜ ์žˆ์„ ๋•Œ, ๊ทธ๋Ÿฌํ•œ ๊ทธ๋ž˜ํ”„๋ฅผ ํŠน๋ณ„ํžˆ ์ด๋ถ„ ๊ทธ๋ž˜ํ”„ (Bipartite Graph) ๋ผ ๋ถ€๋ฅธ๋‹ค.

๊ทธ๋ž˜ํ”„๊ฐ€ ์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์กŒ์„ ๋•Œ, ์ด ๊ทธ๋ž˜ํ”„๊ฐ€ ์ด๋ถ„ ๊ทธ๋ž˜ํ”„์ธ์ง€ ์•„๋‹Œ์ง€ ํŒ๋ณ„ํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

 

ํ’€์ด

  • bfs๋กœ ์ˆœํšŒํ•˜๋ฉด์„œ ๋‘ ๊ฐ€์ง€ ์ƒ‰์œผ๋กœ ์น ํ•˜๊ธฐ (1, -1)
  • ์ด๋ฏธ ์น ํ•ด์ง„ ๊ณณ์ด ๋‹ค๋ฅธ ์ƒ‰์œผ๋กœ ์น ํ•ด์ ธ์•ผ ํ•œ๋‹ค๋ฉด ์ด๋ถ„ ๊ทธ๋ž˜ํ”„๊ฐ€ ์•„๋‹˜

 

์ฝ”๋“œ

#include <iostream>
#include <vector>
#include <queue>
#include <string>

using namespace std;
vector<int> vec[20001];

bool bfs(vector<int>& check, int start) {
    queue<int> que;
    que.push(start);
    while (!que.empty()) {
        int tmp = que.front(); que.pop();
        int comp = check[tmp]; // ๋น„๊ต ๊ฐ’
        for (int i = 0; i < vec[tmp].size(); i++) {
            int tmp2 = vec[tmp][i];
            if (check[tmp2] == comp) {
                // ์ด๋ถ„ ๊ทธ๋ž˜ํ”„ x
                return false;
            }
            if (check[tmp2] != 0)
                // ์ด๋ฏธ ๋“ค๋ฅธ ๊ณณ
                continue;
            check[tmp2] = comp * (-1);
            que.push(tmp2);
        }
    }
    return true;
}

int main() {
    // r,b ์ƒ‰์น ํ•˜๊ธฐ
    // ๊ทธ๋ž˜ํ”„ ํ‘œํ˜„ ( ์—ฐ๊ฒฐ ๋ฆฌ์ŠคํŠธ )
    // bfs๋กœ ๋Œ๋ฉด์„œ ์ƒ‰ ๊ฒน์น˜๋ฉด no

    int K; cin >> K;
    vector<string> answer;

    while (K--) {
        int V, E; cin >> V >> E;
        for (int i = 1; i <= V; i++) {
            vec[i].clear();
        }
        for (int i = 0; i < E; i++) {
            int s, e; cin >> s >> e;
            vec[s].push_back(e);
            vec[e].push_back(s);
        }

        vector<int> check(V + 1, 0);
        int flag = false;
        for (int i = 1; i <= V; i++) {
            if (check[i] != 0) // ์ด๋ฏธ ๋“ค๋ฅธ ๊ณณ์€ ๋‹ค์‹œ ๋ณด์ง€ x
                continue;
            else
                check[i] = 1; // ๋“ค๋ฅด์ง€ ์•Š์€ ๊ณณ์€ 1๋กœ ์‹œ์ž‘
            if (!bfs(check, i)) {
                answer.push_back("NO");
                flag = true;
                break;
            }
        }
        if (!flag)
            answer.push_back("YES");
    }
    for (int i = 0; i < answer.size(); i++) {
        cout << answer[i] << '\n';
    }
}

 

๊ฒฐ๊ณผ

๋ฐ˜์‘ํ˜•