문제링크 : https://www.acmicpc.net/problem/1167

 

1167번: 트리의 지름

트리가 입력으로 주어진다. 먼저 첫 번째 줄에서는 트리의 정점의 개수 V가 주어지고 (2≤V≤100,000)둘째 줄부터 V개의 줄에 걸쳐 간선의 정보가 다음과 같이 주어진다. (정점 번호는 1부터 V까지 매겨져 있다고 생각한다) 먼저 정점 번호가 주어지고, 이어서 연결된 간선의 정보를 의미하는 정수가 두 개씩 주어지는데, 하나는 정점번호, 다른 하나는 그 정점까지의 거리이다. 예를 들어 네 번째 줄의 경우 정점 3은 정점 1과 거리가 2인 간선으로 연결되

www.acmicpc.net

트리의 지름을 구하는 문제다. 트리의 지름이란, 트리에서 가장 멀리 떨어져있는 두 노드 사이의 길이를 말한다.

 

트리의 지름을 구하는 방법은, 임의의 노드 x에서 DFS 백트래킹을 통해 가장 멀리 떨어져있는 노드 y를 구한 후, y에서 다시 DFS 백트래킹을 통해 가장 멀리 떨어져있는 노드 z를 구하면, y에서 z사이의 거리가 바로 트리의 지름이 된다. 이에 대한 증명을 해보자 -> (업데이트 예정)

 

코드는 아래와 같다.

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
74
75
76
77
 
public class Main {
    private static int max = 0;
    private static int start = 0;
    
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int v = Integer.parseInt(br.readLine());
        
        @SuppressWarnings("unchecked")
        List<Link>[] lists = new ArrayList[v + 1];
        
        for(int i = 1; i <= v; i++) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            int n = Integer.parseInt(st.nextToken());
            lists[n] = new ArrayList<Link>();
            
            while(true) {
                int m = Integer.parseInt(st.nextToken());
                
                if(m == -1break;
                
                lists[n].add(new Link(m, Integer.parseInt(st.nextToken())));
            }
        }
                
        boolean[] visited = new boolean[v + 1];
        dfs(lists, visited, 10);
        
        visited = new boolean[v + 1];
        dfs(lists, visited, start, 0);
        
        System.out.println(max);
    } 
    
    private static void dfs(List<Link>[] lists, boolean[] visited, int i, int length) {
        visited[i] = true;
        
        if(length > max) {
            max = length;
            start = i;
        }
        
        for(Link next : lists[i]) {
            int m = next.getM();
            int distance = next.getDistance();
            
            if(!visited[m]) {
                dfs(lists, visited, m, length + distance);
                visited[m] = false;
            }
        }
    }
 
    private static class Link {
        private int m;
        private int distance;
        
        public Link(int m, int distance) {
            this.m = m;
            this.distance = distance;
        }
 
        public int getM() {
            return m;
        }
 
        public int getDistance() {
            return distance;
        }    
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 

+ Recent posts