๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๐Ÿ“ ์•Œ๊ณ ๋ฆฌ์ฆ˜/BOJ

[C++/BOJ] 1325 : ํšจ์œจ์ ์ธ ํ•ดํ‚น (BFS/DFS)

728x90

๋ฌธ์ œ

ํ•ด์ปค ๊น€์ง€๋ฏผ์€ ์ž˜ ์•Œ๋ ค์ง„ ์–ด๋Š ํšŒ์‚ฌ๋ฅผ ํ•ดํ‚นํ•˜๋ ค๊ณ  ํ•œ๋‹ค. ์ด ํšŒ์‚ฌ๋Š” N๊ฐœ์˜ ์ปดํ“จํ„ฐ๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๋‹ค. ๊น€์ง€๋ฏผ์€ ๊ท€์ฐฎ๊ธฐ ๋•Œ๋ฌธ์—, ํ•œ ๋ฒˆ์˜ ํ•ดํ‚น์œผ๋กœ ์—ฌ๋Ÿฌ ๊ฐœ์˜ ์ปดํ“จํ„ฐ๋ฅผ ํ•ดํ‚น ํ•  ์ˆ˜ ์žˆ๋Š” ์ปดํ“จํ„ฐ๋ฅผ ํ•ดํ‚นํ•˜๋ ค๊ณ  ํ•œ๋‹ค.

์ด ํšŒ์‚ฌ์˜ ์ปดํ“จํ„ฐ๋Š” ์‹ ๋ขฐํ•˜๋Š” ๊ด€๊ณ„์™€, ์‹ ๋ขฐํ•˜์ง€ ์•Š๋Š” ๊ด€๊ณ„๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๋Š”๋ฐ, A๊ฐ€ B๋ฅผ ์‹ ๋ขฐํ•˜๋Š” ๊ฒฝ์šฐ์—๋Š” B๋ฅผ ํ•ดํ‚นํ•˜๋ฉด, A๋„ ํ•ดํ‚นํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ์†Œ๋ฆฌ๋‹ค.

์ด ํšŒ์‚ฌ์˜ ์ปดํ“จํ„ฐ์˜ ์‹ ๋ขฐํ•˜๋Š” ๊ด€๊ณ„๊ฐ€ ์ฃผ์–ด์กŒ์„ ๋•Œ, ํ•œ ๋ฒˆ์— ๊ฐ€์žฅ ๋งŽ์€ ์ปดํ“จํ„ฐ๋ฅผ ํ•ดํ‚นํ•  ์ˆ˜ ์žˆ๋Š” ์ปดํ“จํ„ฐ์˜ ๋ฒˆํ˜ธ๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

์ž…๋ ฅ

์ฒซ์งธ ์ค„์—, N๊ณผ M์ด ๋“ค์–ด์˜จ๋‹ค. N์€ 10,000๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์ž์—ฐ์ˆ˜, M์€ 100,000๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์ž์—ฐ์ˆ˜์ด๋‹ค. ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ M๊ฐœ์˜ ์ค„์— ์‹ ๋ขฐํ•˜๋Š” ๊ด€๊ณ„๊ฐ€ A B์™€ ๊ฐ™์€ ํ˜•์‹์œผ๋กœ ๋“ค์–ด์˜ค๋ฉฐ, "A๊ฐ€ B๋ฅผ ์‹ ๋ขฐํ•œ๋‹ค"๋ฅผ ์˜๋ฏธํ•œ๋‹ค. ์ปดํ“จํ„ฐ๋Š” 1๋ฒˆ๋ถ€ํ„ฐ N๋ฒˆ๊นŒ์ง€ ๋ฒˆํ˜ธ๊ฐ€ ํ•˜๋‚˜์”ฉ ๋งค๊ฒจ์ ธ ์žˆ๋‹ค.

์ถœ๋ ฅ

์ฒซ์งธ ์ค„์—, ๊น€์ง€๋ฏผ์ด ํ•œ ๋ฒˆ์— ๊ฐ€์žฅ ๋งŽ์€ ์ปดํ“จํ„ฐ๋ฅผ ํ•ดํ‚นํ•  ์ˆ˜ ์žˆ๋Š” ์ปดํ“จํ„ฐ์˜ ๋ฒˆํ˜ธ๋ฅผ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ถœ๋ ฅํ•œ๋‹ค.


 

์‹ค๋ฒ„1 

bfs๋กœ๋„ ํ’€ ์ˆ˜ ์žˆ์ง€๋งŒ.. dfs ํ’€์ด๊ฐ€ ๋” ์งง๊ณ  ๊ฐ„๊ฒฐํ•˜๋‹ค.

์ด์ฐจ์›๋ฐฐ์—ด๋กœ ํ’€๋ฉด ๋ฉ”๋ชจ๋ฆฌ ์ดˆ๊ณผ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค๊ณ  ํ•ด์„œ ์ผ์ฐจ์›๋ฐฐ์—ด๊ณผ ๋ฒกํ„ฐ๋กœ ํ’€์—ˆ๋‹ค!

 

matrix ํ˜•์‹์˜ ์ƒํ•˜์ขŒ์šฐ ํƒ์ƒ‰์€ ์ข€ ์‰ฌ์šด๋ฐ, ์˜คํžˆ๋ ค ์ด๋Ÿฐ ๋ฌธ์ œ๊ฐ€ ๋” ํ—ท๊ฐˆ๋ฆฌ๋Š”๋“ฏ..

 

 

 

๋‚˜์˜ ํ’€์ด

#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;

int n;
int m;
const int MAX = 10001;
vector<int> map[MAX];
int visited[MAX];
queue<int> q;
vector<pair<int, int>> v; // <์ปดํ“จํ„ฐ ๋ฒˆํ˜ธ, ํ•ดํ‚น ๊ฐ€๋Šฅํ•œ ์ปดํ“จํ„ฐ ์ˆ˜> ๋ฒกํ„ฐ
int canHack = 0; // ํ•ดํ‚น ๊ฐ€๋Šฅํ•œ ์ปดํ“จํ„ฐ ์ˆ˜

void resetV(){
    for (int i = 0; i <= n; ++i){
        visited[i] = 0;
    }
}

void dfs(int i){
    visited[i] = 1;
    canHack++;
    for(auto k: map[i]){
        if(!visited[k]) {
            dfs(k);
        }
    }
}

int main(){
    ios_base::sync_with_stdio(false);
	cin.tie(NULL);
    cin >> n >> m;
    int a;
    int b;
    for (int i = 0; i < m; ++i){
        cin >> a >> b;
        map[b].push_back(a);
    }
    for (int i = 1; i <= n; ++i){
        dfs(i);
        resetV();
        v.push_back({canHack, i});
        // cout << canHack << " / " << i << "\n";
        canHack = 0;
    }

    sort(v.begin(), v.end(), greater<>());
    int maxHack = v[0].first;
    vector<int> answer;

    for (auto i: v){
        if(i.first == maxHack) answer.push_back(i.second);
        else break;
    }
    sort(answer.begin(), answer.end());
    for(int i: answer) cout << i << " ";
}
728x90