-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
32 additions
and
24 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,28 +1,36 @@ | ||
"use strict"; | ||
|
||
const fs = require("fs"); | ||
const filePath = process.platform === "linux" ? "/dev/stdin" : "input.txt"; | ||
let input = fs.readFileSync(filePath).toString().trim().split("\n"); | ||
const [N, ...input] = require("fs") | ||
.readFileSync("/dev/stdin") | ||
.toString() | ||
.trim() | ||
.split("\n"); | ||
|
||
let n = Number(input[0]); | ||
let arr = new Array(n); | ||
for (let i = 0; i < n; i++) { | ||
let [a, b] = input[i + 1].split(" ").map(Number); | ||
arr[i] = [a, b]; | ||
} | ||
arr.sort((a, b) => a[0] - b[0]); | ||
const solution = (N, input) => { | ||
let poses = input | ||
.map((line) => line.split(" ").map((v) => +v)) | ||
.sort((a, b) => a[0] - b[0]); // x좌표 기준 오름차순으로 정렬하기 | ||
|
||
let ans = 0; | ||
ans += arr[0][1] - arr[0][0]; | ||
let cur = arr[0][1]; | ||
for (let i = 1; i < n; i++) { | ||
if (arr[i][0] <= cur && arr[i][1] > cur) { | ||
ans += arr[i][1] - cur; | ||
cur = arr[i][1]; | ||
} | ||
if (arr[i][0] > cur) { | ||
ans += arr[i][1] - arr[i][0]; | ||
cur = arr[i][1]; | ||
let answer = 0; | ||
answer += poses[0][1] - poses[0][0]; // 첫번째 y-x 차를 구해 더한다. | ||
let now = poses[0][1]; // 현재 직선의 끝 점 | ||
|
||
for (let i = 1; i < N; i++) { | ||
if (poses[i][0] <= now && poses[i][1] > now) { | ||
// 현재 직선의 x좌표가 now보다 작은 경우 | ||
// 무조건 겹치는 부분이 생기는 직선 | ||
// 현재 직선의 y좌표를 보고 now보다 작으면 겹쳐지는 직선이므로 continue, now보다 크면 길이의 총 합이 증가할 수 있는 직선이므로 poses[i][1] - now를 answer에 더해주고 now 좌표를 갱신 | ||
answer += poses[i][1] - now; | ||
now = poses[i][1]; | ||
} | ||
if (poses[i][0] > now) { | ||
// 현재 직선의 x좌표가 now보다 큰 경우 | ||
// 새로운 직선의 시작점을 찍어야 하는 경우이다. poses[i][1] - poses[i][0] 을 answer에 더해주고 now 좌표를 갱신 | ||
answer += poses[i][1] - poses[i][0]; | ||
now = poses[i][1]; | ||
} | ||
} | ||
} | ||
console.log(ans); | ||
return answer; | ||
}; | ||
|
||
console.log(solution(+N, input)); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters