![[BOJ1967] 트리의 지름(dfs, 인접 리스트)](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FclZoSW%2Fbtsvb2fjNkq%2FdFtYqYvUSqxKKAnDHz1uJK%2Fimg.png)

[BOJ1967] 트리의 지름(dfs, 인접 리스트)알고리즘/트리2023. 9. 21. 20:20
반응형

문제링크
https://www.acmicpc.net/problem/1967
1967번: 트리의 지름
파일의 첫 번째 줄은 노드의 개수 n(1 ≤ n ≤ 10,000)이다. 둘째 줄부터 n-1개의 줄에 각 간선에 대한 정보가 들어온다. 간선에 대한 정보는 세 개의 정수로 이루어져 있다. 첫 번째 정수는 간선이 연
www.acmicpc.net
문제풀이
- 인접 리스트 사용해서 DFS 탐색 2번 수행
- 시간 복잡도 : O(V + E)
절차
1) 1번 루트 노드에서 가장 비용이 큰 리프(leaf)노드를 찾음 (= 지름에 해당하는 한점)
2) 찾은 리프 노드를 시작점으로 dfs 탐색을 한번 더 수행하여 구한 최대 cost가 트리의 지름이다
참고. 동일 문제
https://dev-ljw1126.tistory.com/370
[BOJ1167] 트리의 지름 (트리)
문제 링크 https://www.acmicpc.net/problem/1167 1167번: 트리의 지름 트리가 입력으로 주어진다. 먼저 첫 번째 줄에서는 트리의 정점의 개수 V가 주어지고 (2 ≤ V ≤ 100,000)둘째 줄부터 V개의 줄에 걸쳐 간선
dev-ljw1126.tistory.com
제출코드
import java.util.*;
import java.io.*;
public class Main {
static int N;
static List<Edge>[] adj;
static boolean[] visit;
static int MAX = 0;
static int LEAF;
static class Edge {
int idx;
int cost;
public Edge(int idx, int cost) {
this.idx = idx;
this.cost = cost;
}
}
static void input() throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
N = Integer.parseInt(br.readLine()); // 노드 수
adj = new ArrayList[N + 1];
for(int i = 0; i <= N; i++) adj[i] = new ArrayList<>(); // 0번노드 초기화 안하니 NPE발생
for(int i = 1; i <= N - 1; i++) {
st = new StringTokenizer(br.readLine());
int from = Integer.parseInt(st.nextToken());
int to = Integer.parseInt(st.nextToken());
int cost = Integer.parseInt(st.nextToken());
adj[from].add(new Edge(to, cost));
adj[to].add(new Edge(from, cost));
}
}
static void dfs(int idx, int cost) {
visit[idx] = true;
if(MAX < cost) {
MAX = cost;
LEAF = idx;
}
for(Edge next : adj[idx]) {
if(!visit[next.idx]) {
dfs(next.idx, cost + next.cost);
}
}
}
static void pro() {
visit = new boolean[N + 1];
dfs(1, 0);
Arrays.fill(visit, false);
dfs(LEAF, 0);
System.out.println(MAX);
}
public static void main(String[] args) throws Exception {
input();
pro();
}
}
반응형
'알고리즘 > 트리' 카테고리의 다른 글
[BOJ2263] 트리의 순회(분할 정복) (0) | 2024.02.24 |
---|---|
[BOJ1167] 트리의 지름 (트리) (0) | 2023.09.07 |
[BOJ 14267] 회사 문화1 (Java, DFS, Tree) (0) | 2023.06.26 |
[BOJ 1068] 트리 (Java, DFS) (0) | 2023.06.26 |
[BOJ 9489] 사촌 (Java, 트리) (0) | 2023.06.26 |

@leejinwoo1126 :: 천천히 하나씩
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!