๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm๐Ÿฐ/๋ฐฑ์ค€

[๋ฐฑ์ค€] 2617 ๊ตฌ์Šฌ ์ฐพ๊ธฐ DFS

by Jouureee 2021. 2. 26.

๋ฌธ์ œ :

www.acmicpc.net/problem/2617

 

2617๋ฒˆ: ๊ตฌ์Šฌ ์ฐพ๊ธฐ

๋ชจ์–‘์€ ๊ฐ™์œผ๋‚˜, ๋ฌด๊ฒŒ๊ฐ€ ๋ชจ๋‘ ๋‹ค๋ฅธ N๊ฐœ์˜ ๊ตฌ์Šฌ์ด ์žˆ๋‹ค. N์€ ํ™€์ˆ˜์ด๋ฉฐ, ๊ตฌ์Šฌ์—๋Š” ๋ฒˆํ˜ธ๊ฐ€ 1,2,...,N์œผ๋กœ ๋ถ™์–ด ์žˆ๋‹ค. ์ด ๊ตฌ์Šฌ ์ค‘์—์„œ ๋ฌด๊ฒŒ๊ฐ€ ์ „์ฒด์˜ ์ค‘๊ฐ„์ธ (๋ฌด๊ฒŒ ์ˆœ์„œ๋กœ (N+1)/2๋ฒˆ์งธ) ๊ตฌ์Šฌ์„ ์ฐพ๊ธฐ ์œ„ํ•ด์„œ

www.acmicpc.net

 

๋ถ„์„ :

์ด ๋ฌธ์ œ๋Š” ๋ฐฐ์—ด์„ ๋‘๊ฐœ๋กœ ๋‚˜๋ˆ ์„œ ์“ธ ์ƒ๊ฐ์„ ๋ชปํ•ด์„œ ๋ฐฐ์—ด์„ ์–ด๋–ป๊ฒŒ ๋‹ด์•„์•ผ ํ•˜๋Š”์ง€ ํƒ€์ž…์— ๊ด€ํ•ด ๊ณ ๋ฏผ์ด ๋งŽ์•˜๋‹ค. ์‹ฌ์ง€์–ด ๋‚ด๊ฐ€ ์ž˜ ๋ชป์“ฐ๋Š” ์žฌ๊ท€ํ•จ์ˆ˜๊นŒ์ง€ ์‚ฌ์šฉํ•ด์„œ ๊ฐ ์žก๊ธฐ๊ฐ€ ์–ด๋ ค์› ๋‹ค ๐Ÿ˜…

๋ฌธ์ œ์—์„œ ์›ํ•˜๋Š” ๊ฒƒ์€ ๋ฌด๊ฒŒ๊ฐ€ ์ค‘๊ฐ„์ด ๋  ์ˆ˜ ์—†๋Š” ๊ตฌ์Šฌ์˜ ์ˆ˜๋ฅผ ์ฐพ์œผ๋ผ๊ณ  ํ•œ๋‹ค.

์ค‘๊ฐ„์ด ๋  ์ˆ˜ ์—†์œผ๋ ค๋ฉด ๊ฐ๊ฐ ๋‹ด์€ light, heavy vector์— ์ธ์ ‘ํ•œ ๋…ธ๋“œ๋“ค์ด ๋งŽ์ด ๋‹ด๊ฒจ ๋น„๊ต๊ฐ€ ๋งŽ์ด ๋˜์–ด์•ผ ํ•œ๋‹ค. 

๋”ฐ๋ผ์„œ dfs ๋ฅผ ๋Œ๋•Œ๋งˆ๋‹ค lank ๊ฐ’์ด ์ฆ๊ฐ€ํ•˜๊ณ  ์ค‘๊ฐ„ ์ด์ƒ์˜ ๊ฐ’์„ ๊ฐ€์ง„ ๋…ธ๋“œ์— ๋Œ€ํ•ด check ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด ์ €์žฅํ•ด ๋†“๋Š”๋‹ค. 

๋ฌธ์ œ์˜ ๋œป์„ ํŒŒ์•…ํ–ˆ๋‹ค๋ฉด ์ „ํ˜•์ ์ธ dfs ๋ฌธ์ œ๋กœ ๋ณด์ผ ๋“ฏ ํ•˜๋‹ค. 

 

 

c++ ์ฝ”๋“œ :

//
//  2617_ใ…กmarble.cpp
//  SOMA๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป
//
//  Created by JoSoJeong on 2021/02/11.
//

#include <stdio.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <string.h>
#include <stack>

using namespace std;

#define MAX 101
int n, N;
bool visit[2][MAX];
vector<int> light[MAX];
vector<int> heavy[MAX];
bool check[MAX];
int cnt = 0;

int find_marble_dfs(int start, vector<int> graph[MAX], int row){//row ๋กœ graph == heavy, light ์ธ์ง€ ํŒ๋ณ„
    int Lank = 1; // ํ˜„์žฌ ์ˆœ์œ„
    for(int i = 0; i < (int)graph[start].size(); i++){
        if(visit[row][graph[start][i]] == false){
            visit[row][graph[start][i]] = true; // dfs ๋Œ ์ˆ˜๋ก ๋น„๊ตํ•  ๊ตฌ์Šฌ์ด ๋งŽ๋‹ค๋Š” ๊ฒƒ ๋”ฐ๋ผ์„œ ์ˆœ์œ„ ํฌ๊ธฐ๊ฐ€ ์ฆ๊ฐ€ (ex> 1 -> 8)
            Lank += find_marble_dfs(graph[start][i], graph, row);
        }
    }
    return Lank;
}


int main(){
    int n, N;
    cin >> n >> N;

    for(int i = 0; i< N; i++){
        int m1, m2; //m1 > m2
        cin >> m1 >> m2;
        light[m1].push_back(m2);
        heavy[m2].push_back(m1);
    }

    for (int i = 1; i <= n; i++) { // n = ๊ตฌ์Šฌ ๋ฒˆํ˜ธ 1 ~ n
        memset(visit, false, sizeof(visit));
        visit[0][i] = visit[1][i] = true;

        int h_rank = find_marble_dfs(i, heavy, 0);
        int l_Lank = find_marble_dfs(i, light, 1);

        if (h_rank > (n + 1) / 2 || l_Lank > (n + 1) / 2){ // ์ค‘๊ฐ„์ด ์•„๋‹Œ ๊ตฌ์Šฌ๋“ค check
            check[i] = true;
        }
    }

    for (int i = 0; i <= n; i++){
        if (check[i] == true){
            cnt++; //
        }
    }

    cout << cnt << endl;
        return 0;
}

๋Œ“๊ธ€