티스토리 뷰
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
'자료구조 알고리즘 > 백준' 카테고리의 다른 글
Node.js) 백준 16946번: 벽 부수고 이동하기 4 (0) | 2022.08.03 |
---|---|
Node.js)백준 14442번: 벽 부수고 이동하기 2 (0) | 2022.08.03 |
Node.js) 백준 16940번: BFS 스페셜 저지 (0) | 2022.07.31 |
Node.js)백준 19236번: 청소년 상어 (0) | 2022.07.13 |
Node.js)백준 13460번: 구슬 탈출 2 (0) | 2022.07.12 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- MySQL
- 다이나믹프로그래밍
- 동적프로그래밍
- create db
- DB 생성
- 은둔청년체험
- 롱베케이션
- node.js
- 서버개발
- 투포인터 연습
- 개발자면접
- 그래프
- 최소공통조상
- BFS
- create databases;
- 면접질문
- KMP
- 다이나밍프로그래밍
- MOD
- 로드나인
- 면접비
- 서버점검
- 투포인터
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함