Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- BOJ
- RequiredArgsConstructor
- SSAFY #싸피 #7기 #합격 #개발
- Java
- SQL
- 면접합격
- pymysql
- IntelliJ
- mybatis
- 윈도우우분투
- UnsupportedOperationException
- 프로젝트회고록
- BFG
- github
- 커밋옮기기
- commit
- SSAFY
- window
- JsonObect
- 백준
- 이중우선순위큐
- 백엔드
- 추가합격
- 의존성주입
- 삼성 #교육 #개발자 #웹
- tmehz
- treeset
- 프로시저
- gitlab
- 싸피
Archives
- Today
- Total
데굴데굴 굴러가는 개발 블로그
백준 BOJ 1967 JAVA / 트리의 지름 본문
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class 백준_S3_11659_구간합구하기4 {
static int dist, farNode;
static ArrayList<Node> tree[];
static boolean[] isVisited;
public static class Node{ // 위치, 가중치
int pos;
int weight;
Node(int pos, int weight){
this.pos = pos;
this.weight = weight;
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int N = Integer.parseInt(br.readLine());
dist = 0;
farNode = 0;
tree = new ArrayList[N+1];
isVisited = new boolean[N+1];
// tree 초기화 (하나의 노드에는 두개 이상의 자식이 있을 수 있기 때문에 ArrayList로 초기값 채워주기)
for(int i = 0 ; i < N+1; i++){
tree[i] = new ArrayList<>();
}
// input 처리
for(int i=0; i<N-1; i++){
st = new StringTokenizer(br.readLine());
int parent = Integer.parseInt(st.nextToken());
int child = Integer.parseInt(st.nextToken());
int weight = Integer.parseInt(st.nextToken());
tree[parent].add(new Node(child, weight)); // 부모 노드와 연결
tree[child].add(new Node(parent,weight)); // 자식 노드와 연결
}
// 맨 처음부터 시작해서 -> 가장 거리가 먼 곳을 지정한다. -> 해당 지점에서 가장 거리가 먼 지점까지의 거리가 트리의 지름이 된다.
isVisited[1] = true; // 첫노드는 방문 처리해주기
DFS(1,0); // 가장 거리가 먼 노드 찾아내기
isVisited = new boolean[N+1]; // 방문기록 초기화
dist = 0; // 거리 초기화
isVisited[farNode] = true; // 첫노드는 방문 처리해주기
DFS(farNode, 0); // 맨 끝이므로 여기서 가장 먼 노드를 찾아내면 된다.
System.out.println(dist);
}
public static void DFS(int nodeNum, int totalDist){
if(dist < totalDist){ // 최장거리 노드 갱신
dist = totalDist;
farNode = nodeNum;
}
for(Node nNode : tree[nodeNum]){
if(isVisited[nNode.pos]) continue; // 중복방문 제거
isVisited[nNode.pos] = true; // 방문 처리
DFS(nNode.pos, totalDist+nNode.weight);
}
}
}
회사 다니면서 코테 재활하기 힘들다....
다 잘해놓고 제일 먼 노드 구하고 첫 노드 방문처리 안해서 86퍼에서 계속 틀렸습니다 떴다.. 진짜 제발 꼼꼼하게 풀자..^^
'알고리즘 > 문제 풀이' 카테고리의 다른 글
백준 2239 스도쿠 ( java ) (2) | 2022.04.06 |
---|---|
백준 2309 일곱 난쟁이 JAVA (0) | 2022.02.15 |