Pepperminttt
Pepperminttt's Dev
Pepperminttt
전체 방문자
오늘
어제
  • devInfo (86)
    • forBeingGoodDeveloper (2)
    • React (2)
      • LostArk Open API (1)
    • algorithm (58)
      • problems (44)
      • theory (14)
    • computerScience (8)
      • network (8)
    • javaScript (8)
    • Java (4)
    • web (2)
      • webApplication (2)
    • etc. (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 프로그래머스
  • solved.ac
  • 탐욕법
  • BFS
  • 백준
  • dfs문제
  • node.js
  • dfs
  • C++
  • 알고리즘
  • DP
  • JavaScript
  • DP문제
  • greedy
  • Java
  • 그래프
  • 탐욕법 문제
  • Network
  • 벨만-포드
  • bfs문제

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
Pepperminttt

Pepperminttt's Dev

[백준 / Java] 1967번 : 트리의 지름
algorithm/problems

[백준 / Java] 1967번 : 트리의 지름

2023. 7. 29. 10:20

문제

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

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

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

트리의 노드는 1부터 n까지 번호가 매겨져 있다.

입력

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

출력

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

예제 입력 1 복사

12
1 2 3
1 3 2
2 4 5
3 5 11
3 6 9
4 7 1
4 8 7
5 9 15
5 10 4
6 11 6
6 12 10

예제 출력 1 복사

45

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

 

1967번: 트리의 지름

파일의 첫 번째 줄은 노드의 개수 n(1 ≤ n ≤ 10,000)이다. 둘째 줄부터 n-1개의 줄에 각 간선에 대한 정보가 들어온다. 간선에 대한 정보는 세 개의 정수로 이루어져 있다. 첫 번째 정수는 간선이 연

www.acmicpc.net


문제 풀이

 해당 문제는 트리의 지름을 구하는 문제로 점과 점 사이가 가장 긴 거리를 구하면 된다. 간단하게 DFS로도 답을 구할 수는 있으나 노드가 많아진다면 시간 초과가 나올 것이다. 그렇기에 최대한 효율적인 방법으로 답을 구해야 한다.

 

 다익스트라 알고리즘과 간단한 이해만 있으면 트리의 지름을 쉽게 구할 수 있다. 트리의 지름을 구하는 법은 아래와 같다.

 

1. 임의의 점에서 가장 먼 점을 찾는다.

2. 해당 점에서 가장 먼 점과의 거리를 구한다. => 트리의 지름

 

 한 점에서 먼 점은 다른 점에서도 멀다는 것을 이해하고 푼다면 쉽게 이해할 수 있다.

 

2023.07.22 - [algorithm/theory] - 다익스트라(Dijkstra) 알고리즘


풀이 코드

import java.io.*;
import java.util.*;
import java.util.stream.IntStream;
 
public class Main {
	public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	public static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
	public static int INF = 1_000_000;
	public static Map<Integer,ArrayList<Node>> nodes = new HashMap<>();
	public static int T;
	
	
	public static class Node implements Comparable<Node>{
		
		int to;
		int distance;
		
		public Node() {
			
		}

		public Node(int to, int distance) {
			super();
			this.to = to;
			this.distance = distance;
		}

		@Override
		public int compareTo(Node o) {
			
			return this.distance - o.distance;
		}
		
	}
	
	public static void main(String[] args) throws IOException {
		
		T = Integer.parseInt(br.readLine());
		
		if(T == 1) {
			System.out.println(0);
		}else {
			for(int t = 1; t < T; t++) {
				StringTokenizer st =new StringTokenizer(br.readLine());
				
				
				int p1 = Integer.parseInt(st.nextToken());
				int p2 = Integer.parseInt(st.nextToken());
				int distance = Integer.parseInt(st.nextToken());
				
				if(nodes.containsKey(p1)) {
					nodes.get(p1).add(new Node(p2,distance));
				}else {
					ArrayList<Node> temp = new ArrayList<>();
					temp.add(new Node(p2,distance));
					nodes.put(p1,temp);
				}
				if(nodes.containsKey(p2)) {
					nodes.get(p2).add(new Node(p1,distance));
				}else {
					ArrayList<Node> temp = new ArrayList<>();
					temp.add(new Node(p1,distance));
					nodes.put(p2,temp);
				}
				
			}
				int[] first = djikstra(1);
				int max = Arrays.stream(first).reduce(0, (x,v)-> x > v ? x : v);
				int maxIndex = IntStream.range(0, first.length).
		                filter(i -> max == first[i]).
		                findFirst().orElse(-1);
				int[] second = djikstra(maxIndex);
				int answer = Arrays.stream(second).reduce(0, (x,v)-> x > v ? x : v);
				
				System.out.println(answer);
			bw.flush();
			bw.close();
		}
		
	}

	public static int[] djikstra(int start) {
		int[] dp = new int[T+1];
		boolean[] visited= new boolean[T+1];
		PriorityQueue<Node> pq = new PriorityQueue<>();
		
		Arrays.fill(dp, INF);
		dp[0] = 0;
		dp[start] = 0;
		pq.add(new Node(start,0));
		
		while(!pq.isEmpty()) {
			Node cur = pq.poll();
			
			if(visited[cur.to]) continue;
			visited[cur.to] = true;
			
			for(Node next : nodes.get(cur.to)) {
				if(dp[next.to] > dp[cur.to] + next.distance) {
					dp[next.to] = dp[cur.to] + next.distance;
					pq.add(new Node(next.to,dp[next.to]));
				}
			}
		}
		return dp;
	}
}

'algorithm > problems' 카테고리의 다른 글

[백준 / Java] 5639번 : 이진 검색 트리  (0) 2023.08.02
[백준 / Java] 2206번 : 벽 부수고 이동하기  (0) 2023.07.31
[백준 / Java] 1918번 후위 표기식  (0) 2023.07.28
[백준 / Java] 1865번 : 웜홀  (0) 2023.07.27
[백준 / Java] 1504번 : 특정한 최단 경로  (0) 2023.07.24
    'algorithm/problems' 카테고리의 다른 글
    • [백준 / Java] 5639번 : 이진 검색 트리
    • [백준 / Java] 2206번 : 벽 부수고 이동하기
    • [백준 / Java] 1918번 후위 표기식
    • [백준 / Java] 1865번 : 웜홀
    Pepperminttt
    Pepperminttt
    HTML, JavaScript, Python 등 Computer language TIL

    티스토리툴바