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 |
Tags
- 복서 정렬하기
- 부분 수열의 합
- BOJ
- openssl
- 순열장난
- 입실 퇴실
- 1174
- 재귀
- 위클리 6주차
- dfs
- DP
- Java
- BFS
- 좋은 수열
- 39080
- 10597
- 백트랙킹
- 코딩테스트
- 백트래킹
- 줄어드는 숫자
- ElementTree
- 백준
- 프로그래머스
- 위클리 챌린지
- 문서자동화
- 몯느 순열
- 그래프
- 백트렉킹
- 완전 탐색
- 너비우선탐색
Archives
개발자-H 입니다.
BOJ - 트리의 부모 찾기 본문
https://www.acmicpc.net/submit/11725/32749545
로그인
www.acmicpc.net
- 그래트 탐색 문제이다.
- DFS,BFS 어떤 것을 사용해도 무방하다.
- 노드에 이전 노드(부모)를 저장했고 root 배열을 만들어서 표기했다.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
public static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws Exception {
int N = Integer.parseInt(br.readLine());
boolean[] visited = new boolean[N + 1];
int[] root = new int[N + 1];
StringTokenizer st;
ArrayList<Integer>[] adj = new ArrayList[N + 1];
for (int i = 0; i < N + 1; i++) {
adj[i] = new ArrayList<>();
}
for (int i = 0; i < N - 1; i++) {
st = new StringTokenizer(br.readLine());
int source = Integer.parseInt(st.nextToken());
int dest = Integer.parseInt(st.nextToken());
adj[source].add(dest);
adj[dest].add(source);
}
Queue<Node> queue = new LinkedList<>();
queue.offer(new Node(1, 1, 1));
while (!queue.isEmpty()) {
Node currentNode = queue.poll();
if (visited[currentNode.index]) continue;
visited[currentNode.index] = true;
root[currentNode.index] = currentNode.root;
for (int i = 0; i < adj[currentNode.index].size(); i++) {
Integer nextNode = adj[currentNode.index].get(i);
if (visited[nextNode]) continue;
queue.offer(new Node(currentNode.index, nextNode, currentNode.depth + 1));
}
}
for (int i = 2; i < N + 1; i++) {
System.out.println(root[i]);
}
}
static class Node {
public int root;
public int index;
public int depth;
public Node(int root, int index, int depth) {
this.root = root;
this.index = index;
this.depth = depth;
}
}
}
'Algorithm > 문제 풀이' 카테고리의 다른 글
BOJ - 듣보잡 (0) | 2021.08.31 |
---|---|
BOJ - A -> B (0) | 2021.08.31 |
BOJ - 부녀회장이 될테야 (0) | 2021.08.29 |
BOJ - 좌표 정렬하기 (0) | 2021.08.28 |
프로그래머스 - 카카오프렌즈 컬러링북 (0) | 2021.08.17 |