Post

[C++]백준 6118번 숨바꼭질

[C++]백준 6118번 숨바꼭질

📌문제 링크


https://www.acmicpc.net/problem/6118

📌문제 설명


1번부터 bfs탐색을 하며 제일 먼거리를 찾으면 된다. 현재 최대거리보다 더 먼 노드를 찾으면 노드 인덱스, 거리, 개수를 초기화 해준다.

📌코드


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
vector<int> graph[20001];
bool visited[20001];
int N, M, answerIdx = 214341231, answerDist, answerCnt;

void input(){
    cin >> N >> M;
    for(int i = 0; i < M; i++){
        int a, b;
        cin >> a >> b;
        graph[a].push_back(b);
        graph[b].push_back(a);
    }
}

void bfs(){
    queue<pair<int, int>> q;
    q.push({1, 0});
    visited[1] = true;
    while(!q.empty()){
        auto [idx, dist] = q.front();
        q.pop();
        if(answerDist == dist && idx != 1){
            answerCnt++;
            answerIdx = min(answerIdx, idx);
        }
        else if(answerDist < dist){
            answerDist = dist;
            answerIdx = idx;;
            answerCnt = 1;
        }
        for(auto it : graph[idx]){
            if(!visited[it]){
                visited[it] = true;
                q.push({it, dist + 1});
            }
        }
    }
    cout << answerIdx << ' ' << answerDist << ' ' << answerCnt;
}

void solve(){
    input();
    bfs();
}

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    solve();
    return 0;
}
This post is licensed under CC BY 4.0 by the author.