티스토리 뷰

https://www.acmicpc.net/problem/16964

 

16964번: DFS 스페셜 저지

첫째 줄에 정점의 수 N(2 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N-1개의 줄에는 트리의 간선 정보가 주어진다. 마지막 줄에는 DFS 방문 순서가 주어진다. DFS 방문 순서는 항상 N개의 정수로 이루

www.acmicpc.net

class Node {
  constructor(item) {
    this.item = item;
    this.prev = null;
  }
}

class Stack {
  constructor() {
    this.top = null;
    this.length = 0;
  }

  push(item) {
    const node = new Node(item);
    if (this.top != null) {
      node.prev = this.top;
    }
    this.top = node;
    this.length++;
  }

  pop() {
    if (this.length > 0) {
      const popItem = this.top;
      this.top = this.top.prev;
      this.length--;
      return popItem.item;
    } else {
      return false;
    }
  }
}

const fs = require("fs");
const input = fs
  .readFileSync("./dev/stdin")
  .toString()
  .trim()
  .split("\n")
  .map((v) => v.split(" ").map(Number));

const [N] = input.shift();
const target = input.pop();

// 우선순위
const priority = [];
for (let i = 0; i < target.length; i++) {
  priority[target[i]] = i;
}

// 인접리스트
let edge = Array.from(Array(N + 1), () => Array());
input.forEach((v) => {
  const [x, y] = v;
  edge[x].push(y);
  edge[y].push(x);
});

//우선순위에 따른 인접 리스트 설정.
edge = edge.map((v) => v.sort((a, b) => priority[b] - priority[a]));

//dfs
const stack = new Stack();
stack.push(1);
let visited = new Array(N + 1).fill(false);
const answer = [];

while (stack.length > 0) {
  const now = stack.pop();
  answer.push(now);
  visited[now] = true;

  edge[now].forEach((v) => {
    if (!visited[v]) {
      stack.push(v);
    }
  });
}

if (answer.join(" ") == target.join(" ")) {
  console.log(1);
} else {
  console.log(0);
}
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/08   »
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
글 보관함