티스토리 뷰

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
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
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
글 보관함