알고리즘/백준

[백준 2660] 회장뽑기 C++

겜도리도리 2021. 10. 5. 23:45
반응형

문제

백준 2660 회장뽑기

풀이

각 정점마다 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <cstring>
using namespace std;
 
vector<int> v[51];
bool visited[51];
int N;
int score[51];
 
// start에서 시작하여 maxdepth를 반환
int bfs(int start) {
    int maxdepth = 0;
    memset(visited, 0sizeof(visited));
    queue<pair<intint>> q;
    q.push(make_pair(start, 0));
    visited[start] = true;
    while (!q.empty()) {
        int node = q.front().first;
        int depth = q.front().second;
        maxdepth = max(maxdepth, depth);
        q.pop();
        for (int i = 0; i < v[node].size(); i++) {
            int next = v[node][i];
            if (!visited[next]) {
                visited[next] = true;
                q.push(make_pair(next, depth+1));
            }
        }
    }
    return maxdepth;
}
 
int main() {
    // 입력
    cin >> N;
    while (1) {
        int a, b;
        cin >> a >> b;
        if (a == -1 && b == -1)
            break;
        v[a].push_back(b);
        v[b].push_back(a);
    }
    int minscore = 987654321;
    int presidentcnt = 0;
    vector<int> president;
 
    for (int i = 1; i <= N; i++) {
        // bfs로 depth 반환
        score[i] = bfs(i);
        // score가 더 작으면 갱신
        if (score[i] < minscore) {
            minscore = score[i];
            presidentcnt = 1;
            president.clear();
            president.push_back(i);
        }
        // 같으면 추가
        else if (score[i] == minscore) {
            presidentcnt++;
            president.push_back(i);
        }
    }
    // 출력
    cout << minscore << ' ' << president.size() << endl;
    for (int i = 0; i < president.size(); i++) {
        cout << president[i] << ' ';
    }
    return 0;
}
cs
반응형

'알고리즘 > 백준' 카테고리의 다른 글

[백준 14719] 빗물 C++  (0) 2021.10.07
[백준 13398] 연속합 2 C++  (0) 2021.10.07
[백준 5582] 공통 부분 문자열 C++  (0) 2021.10.03
[백준 13023] ABCDE C++  (0) 2021.10.02
[백준 1038] 감소하는 수 C++  (0) 2021.10.01