[백준] 트리의 지름(1967)

GGANI·2021년 6월 10일
0

algorithm

목록 보기
13/20

문제

[백준] 트리의 지름(1967)

사진이 첨부되어 있으니 링크를 통해 문제를 확인해주세요.

트리(tree)는 사이클이 없는 무방향 그래프이다. 트리에서는 어떤 두 노드를 선택해도 둘 사이에 경로가 항상 하나만 존재하게 된다. 트리에서 어떤 두 노드를 선택해서 양쪽으로 쫙 당길 때, 가장 길게 늘어나는 경우가 있을 것이다. 이럴 때 트리의 모든 노드들은 이 두 노드를 지름의 끝 점으로 하는 원 안에 들어가게 된다.

이런 두 노드 사이의 경로의 길이를 트리의 지름이라고 한다. 정확히 정의하자면 트리에 존재하는 모든 경로들 중에서 가장 긴 것의 길이를 말한다.

입력으로 루트가 있는 트리를 가중치가 있는 간선들로 줄 때, 트리의 지름을 구해서 출력하는 프로그램을 작성하시오. 아래(입력)와 같은 트리가 주어진다면 트리의 지름은 45가 된다.

입력

파일의 첫 번째 줄은 노드의 개수 n(1 ≤ n ≤ 10,000)이다. 둘째 줄부터 n-1개의 줄에 각 간선에 대한 정보가 들어온다. 간선에 대한 정보는 세 개의 정수로 이루어져 있다. 첫 번째 정수는 간선이 연결하는 두 노드 중 부모 노드의 번호를 나타내고, 두 번째 정수는 자식 노드를, 세 번째 정수는 간선의 가중치를 나타낸다. 간선에 대한 정보는 부모 노드의 번호가 작은 것이 먼저 입력되고, 부모 노드의 번호가 같으면 자식 노드의 번호가 작은 것이 먼저 입력된다. 루트 노드의 번호는 항상 1이라고 가정하며, 간선의 가중치는 100보다 크지 않은 양의 정수이다.

출력

첫째 줄에 트리의 지름을 출력한다.

해설

백준 트리의 지름(1167)문제와 같은 문제로 DFS, BFS 두 가지 방법을 사용해 풀이하였다.

메모리와 시간 모두 큰 차이는 없지만 시간은 DFS < BFS 였다.

DFS

import java.util.*;
import java.io.*;

public class Main {
	static int n;
	static List<Edge>[] edgeList;
	static int[] dist;
	static boolean[] visited;

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		n = Integer.parseInt(br.readLine());

		edgeList = new ArrayList[n + 1];
		dist = new int[n + 1];
		visited = new boolean[n + 1];

		for (int i = 0; i <= n; i++) {
			edgeList[i] = new ArrayList<>();
		}

		StringTokenizer st;

		for (int i = 0; i < n - 1; i++) {
			st = new StringTokenizer(br.readLine(), " ");

			int v = Integer.parseInt(st.nextToken());
			int u = Integer.parseInt(st.nextToken());
			int cost = Integer.parseInt(st.nextToken());

			edgeList[v].add(new Edge(u, cost));
			edgeList[u].add(new Edge(v, cost));
		}

		visited[1] = true;
		dfs(1);
		
		int max = 0, max_idx = 0;
		
		for (int i = 1; i <= n; i++) {
			if(dist[i] > max) {
				max = dist[i];
				max_idx = i;
			}
		}
		
		Arrays.fill(visited, false);
		Arrays.fill(dist, 0);
		
		visited[max_idx] = true;
		dfs(max_idx);
		
		max = 0;
		
		for(int num : dist) {
			max = Math.max(num, max);
		}
		
		System.out.println(max);
	}

	public static void dfs(int u) {
		for(Edge edge : edgeList[u]) {
			if(!visited[edge.v]) {
				visited[edge.v] = true;
				dist[edge.v] = dist[u] + edge.cost;
				dfs(edge.v);
			}
		}
	}

	public static class Edge {
		int v, cost;

		public Edge(int v, int cost) {
			this.v = v;
			this.cost = cost;
		}
	}
}

BFS

import java.util.*;
import java.io.*;

public class Main {
	static int n;
	static List<Edge>[] edgeList;
	static int[] dist;

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		n = Integer.parseInt(br.readLine());

		edgeList = new ArrayList[n + 1];
		dist = new int[n + 1];

		for (int i = 0; i <= n; i++) {
			edgeList[i] = new ArrayList<>();
		}

		StringTokenizer st;

		for (int i = 0; i < n - 1; i++) {
			st = new StringTokenizer(br.readLine(), " ");

			int v = Integer.parseInt(st.nextToken());
			int u = Integer.parseInt(st.nextToken());
			int cost = Integer.parseInt(st.nextToken());

			edgeList[v].add(new Edge(u, cost));
			edgeList[u].add(new Edge(v, cost));
		}

		bfs(1);
		
		int max = 0, max_idx = 0;
		
		for (int i = 1; i <= n; i++) {
			if(dist[i] > max) {
				max = dist[i];
				max_idx = i;
			}
		}
		
		Arrays.fill(dist, 0);
		
		bfs(max_idx);
		
		max = 0;
		
		for(int num : dist) {
			max = Math.max(num, max);
		}
		
		System.out.println(max);
	}

	public static void bfs(int u) {
		Queue<Integer> queue = new LinkedList<>();
		boolean[] visited = new boolean[n + 1];

		queue.add(u);
		visited[u] = true;

		while (!queue.isEmpty()) {
			int v = queue.poll();

			for (Edge node : edgeList[v]) {
				if (!visited[node.v]) {
					visited[node.v] = true;
					dist[node.v] = dist[v] + node.cost;
					queue.add(node.v);
				}
			}
		}
	}

	public static class Edge {
		int v, cost;

		public Edge(int v, int cost) {
			this.v = v;
			this.cost = cost;
		}
	}
}
profile
능력있는 개발자를 꿈꾸는 작은아이

0개의 댓글