Notice
Recent Posts
Recent Comments
Link
«   2024/04   »
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
Archives
Today
Total
관리 메뉴

차근차근

[백준 1167] 트리의 지름 본문

대학교/Algorithm

[백준 1167] 트리의 지름

SWKo 2020. 3. 11. 19:21

0. 제목

  • 백준 1167 트리의 지름
  • BOJ 1167 트리의 지름
  • C++ 1167 트리의 지름

1. 문제

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


2. 풀이

  • 두점 사리의 거리 중 가장 먼 것을 찾아야 하므로 한점을 잡고 그 점으로부터 가장 먼 점을 먼저 찾는다. 찾은 가장 먼 점을 기준으로 잡고 또 다시 그곳으로부터 가장 먼 점을 찾는다.
  • 위와 같은 아이디어를 가지고 시작해보겠다.
  • vector 원소의 자료형으로 pair<int, int>로 설정하였는데, first에는 연결된 정점, second에는 거리를 저장하였다.
  • 가장 먼 점을 구해야 하기 때문에 bfs를 사용하였다.
  • 기준점으로부터의 거리를 저장하는 dist배열을 만든 후 bfs로 한단계를 거칠때마다 그 거리를 더해준 후 저장한다.
  • 첫번째 bfs에서 임의의 점인 1로부터 탐색을 시작하도록 하고 가장 먼 점의 index를 저장한다.
  • 두번째 bfs를 하기전에 visited와 dist를 초기화 시켜주었다.
  • 두번째 bfs를 마친 후 dist의 원소중 최댓값이 정답이다.

3. 코드

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
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
 
#define MAX 100001
vector<pair<intint>> v[MAX];
queue<int> q;
bool visited[MAX];
int dist[MAX];
 
void bfs(int start){
    memset(visited, falsesizeof(visited));
    memset(dist, 0sizeof(dist));
    
    visited[start] = true;
    q.push(start);
    
    while(!q.empty()){
        int node = q.front();
        q.pop();
        
        for(int i = 0; i < v[node].size(); i++){
            int next_node = v[node][i].first;
            if(visited[next_node] == false){
                dist[next_node] = dist[node] + v[node][i].second;
                visited[next_node] = true;
                q.push(next_node);
            }
        }
    }
}
 
int main(int argc, const char * argv[]) {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);cout.tie(NULL);
    int V;
    int a, b, w;
    cin >> V;
    for(int i = 0; i < V; i++){
        cin >> a;
        while(1){
            cin >> b;
            if(b == -1)
                break;
            cin >> w;
            v[a].push_back(make_pair(b, w));
        }
    }
    
    bfs(1);
    
    int start = 1;
    for(int i = 2; i <= V; i++){
        if(dist[i] > dist[start])
            start = i;
    }
    
    bfs(start);
    
    int max = 0;
    for(int i = 1; i <= V; i++){
        if(max < dist[i])
            max = dist[i];
    }
    
    cout << max << '\n';
    
    return 0;
}
 
 

 

'대학교 > Algorithm' 카테고리의 다른 글

[백준 2225] 합분해  (0) 2020.03.14
[백준 9461] 파도반 수열  (0) 2020.03.13
[백준 11725] 트리의 부모 찾기  (0) 2020.03.11
[백준 2869] 달팽이는 올라가고 싶다  (0) 2020.03.09
[백준 11651] 좌표 정렬하기 2  (0) 2020.03.09
Comments