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 |
Tags
- JS프로그래머스
- 익스프레스
- js코테
- 백준js
- 백준알고리즘
- 다이나믹프로그래밍
- HTML
- 백준골드
- 리액트댓글기능
- 백준구현
- 리액트
- JS
- 리액트커뮤니티
- 프로그래머스JS
- 코테
- 자바스크립트
- 백준구현문제
- 프로그래머스코테
- 몽고DB
- dp알고리즘
- 알고리즘
- 백준nodejs
- 백준
- 코딩테스트
- CSS
- css기초
- 안드로이드 스튜디오
- 포이마웹
- HTML5
- 프로그래머스
Archives
- Today
- Total
개발새발 로그
[JS] 백준 1717번 - 집합의 표현 - [런타임 에러 (EACCES)], 자료구조, 분리집합, 서로소집합 알고리즘, 그래프이론 본문
알고리즘/그래프 이론
[JS] 백준 1717번 - 집합의 표현 - [런타임 에러 (EACCES)], 자료구조, 분리집합, 서로소집합 알고리즘, 그래프이론
이즈흐 2023. 8. 10. 01:18https://www.acmicpc.net/problem/1717
📋풀이방법
✅서로소집합 알고리즘을 이용하면 간단하게 풀 수 있다.
https://ydoag2003.tistory.com/22
1. parent라는 N+1 크기의 배열을 생성하고 각각 값을 해당되는 인덱스로 저장한다.
2. unionParent를 통해 a와 b의 값을 동일한 부모노드로 바꾼다.
3. findParent를 통해 a와 b의 부모노드가 같은지 확인하고 같으면 YES 아니면 NO로 출력한다.
🤟내 제출
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
let input = [];
rl.on("line", function (line) {
input.push(line);
}).on("close", function () {
solution(input);
process.exit();
});
function solution(input) {
function getParent(parent, x) {
if (parent[x] == x) return x;
return (parent[x] = getParent(parent, parent[x]));
}
function unionParent(parent, x, y) {
let a = getParent(parent, x);
let b = getParent(parent, y);
if (a < b) parent[b] = a;
else parent[a] = b;
}
function findParent(parent, x, y) {
let a = getParent(parent, x);
let b = getParent(parent, y);
if (a == b) return true;
else false;
}
const [N, M] = input.shift().split(" ").map(Number);
const nodes = input.map((e) => e.split(" ").map(Number));
let parent = Array.from({ length: N + 1 }, (_, idx) => idx);
let result = [];
for (let i = 0; i < M; i++) {
let [H, a, b] = nodes[i];
if (H == 1) {
if (findParent(parent, a, b)) {
result.push("YES");
} else {
result.push("NO");
}
} else {
unionParent(parent, a, b);
getParent(parent, a);
getParent(parent, b);
}
}
console.log(result.join("\n"));
}
💢어려웠던 점
1. 런타임 에러 (EACCES)
이 에러때문에 괜한 시간을 소비했다..
검색해보니 가끔 fs모듈로 인해 이런 에러가 생긴다고한다.
readline을 사용해서 위처럼 다시 코드를 재구성했다.
원래 코드는 아래와 같다.
fs모듈사용한 코드
const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "./input.txt";
let input = fs.readFileSync(filePath).toString().trim();
input = input.replace(/\r/g, "").split("\n");
function getParent(parent, x) {
if (parent[x] == x) return x;
return (parent[x] = getParent(parent, parent[x]));
}
function unionParent(parent, x, y) {
let a = getParent(parent, x);
let b = getParent(parent, y);
if (a < b) parent[b] = a;
else parent[a] = b;
}
function findParent(parent, x, y) {
let a = getParent(parent, x);
let b = getParent(parent, y);
if (a == b) return true;
else false;
}
let [N, M] = input.shift().split(" ").map(Number);
let parent = Array.from({ length: N + 1 }, (_, idx) => idx);
let arr = [];
let result = [];
for (let i = 0; i < M; i++) {
let [H, a, b] = input.shift().split(" ").map(Number);
if (H == 1) {
if (findParent(parent, a, b)) {
result.push("YES");
} else {
result.push("NO");
}
} else {
unionParent(parent, a, b);
getParent(parent, a);
getParent(parent, b);
}
}
console.log(result.join("\n"));
2. readline 사용법
- 일단 아래와 같이 처음을 규칙처럼 작성한다.
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
let input = [];
rl.on("line", function (line) {
input.push(line);
}).on("close", function () {
solution(input);
process.exit();
});
-input.push(line);은 rl.close가 없어 입력을 무한히 받는 것인데 on(close)안에서 sloution함수를 통해 우리가 작성할 코드들을 넣어줘야한다
-나는 그냥 solution안에 안하고 그 안에다가만 하면 되지않나? 했는데 함수로 꺼내지 않으니까 왠지 모르게 작동이 안됐다..
-그래서 코드도 깔끔하게 바꿀겸해서 solution(input)으로 호출하고 아래에 함수를 작성한다.
function solution(input) {
...
const [N, M] = input.shift().split(" ").map(Number);
const nodes = input.map((e) => e.split(" ").map(Number));
...
}
-이런식으로 데이터를 받아오는 것인데 readlin도 잘 숙지해놓자.
728x90
반응형
LIST
'알고리즘 > 그래프 이론' 카테고리의 다른 글
[JS] 백준 1520번 : 내리막 길 - 구현, 그래프이론, DFS, 다이나믹프로그래밍(DP) (0) | 2023.08.16 |
---|---|
[JS] 백준 1916번 : 최소비용 구하기 - 그래프이론, 다익스트라 (0) | 2023.08.13 |
[JS] 백준 2252번 : 줄세우기 - 그래프이론, 위상정렬, 큐 (0) | 2023.08.12 |
[JS] 백준 11404번 : 플로이드 - 그래프이론, 플로이드-와샬 (0) | 2023.08.05 |
[JS] 백준 2206 : 벽 부수고 이동하기 - 그래프, 이론그래프, 탐색너비 우선 탐색 (0) | 2023.08.03 |