[백준/s1] 1931 회의실 배정

foresec·2024년 1월 2일

백준

목록 보기
5/23

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

python

58284kb 264ms Python 3

import sys
input = sys.stdin.readline

N = int(input())
arr = [list(map(int, input().split())) for _ in range(N)]

# 끝나는 시간, 시작시간 순으로 오름차순으로 정렬
arr.sort(key=lambda x: (x[1], x[0]))


# 끝나는 시간보다 시간
cnt = 1
now = arr[0][1]
for i in range(1, N):
    if now <= arr[i][0]:
        now = arr[i][1]
        cnt += 1

print(cnt)

JS

python으로는 별 어려움 없이 풀었는데... JS에서 문제가 발생했다

처음코드

분명 (문제의 조건 상으로는 시작 시간과 끝나는 시간은 231-1보다 작거나 같은 자연수 또는 0이다.라는 점에서) 두 sort가 달라질 이유가 없어보였는데 if문 sort만 정답으로 인정되고 ||으로 구현한 sort문은 정답으로 인정되지 않았다

const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "./1931.txt";
let input = fs.readFileSync(filePath).toString().split("\n")

const N = parseInt(input[0]);
const arr = input.slice(1).map((line) => line.split(" ").map(Number));


// 왜 얘는 되고
arr.sort((a, b) => {
  if (a[1] !== b[1]) {
    return a[1] - b[1];
  } else {
    return a[0] - b[0];
  }
});

// 얘는 안됨???
// arr.sort((a, b) => {
//   return a[1] - b[1] || a[0] - b[0];
// });


let cnt = 1;
let now = arr[0][1];

for (let i = 1; i < N; i++) {
  if (now <= arr[i][0]) {
    now = arr[i][1];
    cnt += 1;
  }
}
console.log(cnt);

도대체 왜그런가 해서 물어보고 다녔더니만...
백준에서 가끔 입력값 오류 때문에 줄바꿈 문자가 마지막에 남아있을 수 있는데 이름 trim해주지 않으면 ""가 마지막에 같이 반환된다
ex)

"Hello\nWorld\n"
//을 trim하지 않고 split하게 되면 하단처럼됨....
["Hello", "World", ""]

그다음 과정을 거치면


let something = ['1 2', '2 4', '3 8', '']
const abc = something.map((line) => line.split(" ").map(Number));
console.log(abc) // [ [ 1, 2 ], [ 2, 4 ], [ 3, 8 ], [ 0 ] ] abc

// 깊은 복사
let abc2 = JSON.parse(JSON.stringify(abc));


abc.sort((a, b) => {
  if (a[1] !== b[1]) {
    return a[1] - b[1];
  } else {
    return a[0] - b[0];
  }
});

abc2.sort((a, b) => {
  return a[1] - b[1] || a[0] - b[0];
});



console.log(abc, "up"); 
// [ [ 1, 2 ], [ 2, 4 ], [ 3, 8 ], [ 0 ] ] up
console.log(abc2,"down"); 
// [ [ 0 ], [ 1, 2 ], [ 2, 4 ], [ 3, 8 ] ] down

이렇게 다른 결과값이 나오게 된다

여기서 조금 더 덧붙여 보자면

const temp = [[-1, 0], []]
const [a, b] = temp

console.log(a[1]- b[1] || a[0] - b[0], "up") // NaN up

console.log((()=> {
	if (a[1] !== b[1]) {
    return a[1] - b[1];
  } else {
    return a[0] - b[0];
  }
})(), "down") // NaN down

추가적인 확인코드

if (0 === false) {
	console.log("0 === false 같음")
	//출력안됨(데이터 형식이 다르기 때문에 일치연산자에서 안통함)
}
if (0 == false) {
	console.log("0 == false 같음")
	//출력됨(동등연사자의 경우 값만 비교하므로 같음이 출력됨)
}

if (NaN == NaN) {
	console.log("NaN == NaN 같음")
} else {
	console.log("NaN == NaN 다름")
	//출력됨
}

if (NaN === NaN) {
	console.log("NaN === NaN 같음")
} else {
	console.log("NaN === NaN 다름")
	//출력됨
}

최종코드

결론은 trim()을 잊지말자

// 사용할 수 있는 회의의 최대 개수
const fs = require("fs");
const filePath = process.platform === "linux" ? "/dev/stdin" : "./1931.txt";
// trim 추가
let input = fs.readFileSync(filePath).toString().trim().split("\n")

const N = parseInt(input[0]);
const arr = input.slice(1).map((line) => line.split(" ").map(Number));

// 끝나는 시간, 시작시간 순으로 오름차순으로 정렬

// 이제 sort문 둘다 됨
arr.sort((a, b) => {
  return a[1] - b[1] || a[0] - b[0];
});


// arr.sort((a, b) => {
//   if (a[1] !== b[1]) {
//     return a[1] - b[1];
//   } else {
//     return a[0] - b[0];
//   }
// });

let cnt = 1;
let now = arr[0][1];

for (let i = 1; i < N; i++) {
  if (now <= arr[i][0]) {
    now = arr[i][1];
    cnt += 1;
  }
}
console.log(cnt)

...sort문이 문제인줄 알았더니 trim이 문제였다니

그리고 어째서 if로 만든 sort문은 trim이 있든없든 작동하는가...

profile
왼쪽 태그보다 시리즈 위주로 구분

0개의 댓글