티스토리 뷰
https://www.acmicpc.net/problem/11725
11725번: 트리의 부모 찾기
루트 없는 트리가 주어진다. 이때, 트리의 루트를 1이라고 정했을 때, 각 노드의 부모를 구하는 프로그램을 작성하시오.
www.acmicpc.net
dfs로 풀었음.
class Node{
constructor(item){
this.item = item;
this.next = null;
}
}
class Queue{
constructor(){
this.head = null;
this.tail = null;
this.length = 0;
}
push(item){
const node = new Node(item)
if(this.head==null){
this.head= node;
}else{
this.tail.next = node;
}
this.tail = node;
this.length +=1;
}
pop(){
const popItem = this.head;
this.head = this.head.next;
this.length -=1;
return popItem.item;
}
}
const fs = require('fs');
const input = fs.readFileSync('./dev/stdin').toString().trim().split('\n').map(str=>str.split(' ').map(Number));
const N = input.shift()[0];
const adj = Array.from(Array(N+1),()=>[]);
const edgeTo = new Array(N+1).fill(null);
edgeTo[1] = 0
input.forEach(v=>{
const [a,b] = v;
adj[a].push(b);
adj[b].push(a);
})
let q = new Queue();
q.push(1);
while(q.length>0){
let now = q.pop();
adj[now].forEach(v=>{
if(edgeTo[v]==null){
edgeTo[v] = now;
q.push(v);
}
})
}
const answer = edgeTo.slice(2,N+1).join('\n')
console.log(answer)
728x90
'자료구조 알고리즘 > 백준' 카테고리의 다른 글
Node.js) 백준 5639번: 이진 검색 트리 (0) | 2021.09.27 |
---|---|
Node.js) 백준 1991번: 트리 순회 (0) | 2021.09.27 |
Node.js) 백준 11404번: 플로이드 (0) | 2021.09.26 |
Node.js) 백준 11657번: 타임머신 (0) | 2021.09.26 |
Node.js) 백준 9370번: 미확인 도착지 (0) | 2021.09.26 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 은둔청년체험
- 투포인터
- 최소공통조상
- 롱베케이션
- 면접비
- 서버개발
- 로드나인
- 다이나믹프로그래밍
- 동적프로그래밍
- MySQL
- create databases;
- node.js
- MOD
- BFS
- 개발자면접
- 투포인터 연습
- DB 생성
- 그래프
- 면접질문
- create db
- 서버점검
- 다이나밍프로그래밍
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함