알고리즘 풀이

그리디 알고리즘

JoyYellow 2022. 8. 4. 11:14

1. 좌표 정렬

const fs = require('fs');
const input = fs.readFileSync("dev/stdin").toString().trim().split("\n");

input.shift()

const arr = input.map(item => item.split(" ").map(Number))
console.log('origin: ', arr)

arr.sort((a, b) => {
  if (a[0] > b[0]) return 1
  else if (a[0] < b[0]) return -1
  else {
    if (a[1] > b[1]) return 1
    else if (a[1] < b[1]) return -1
    else 0
  }
})
// 위의 소스코드를 아래와 같이 간단하게 줄일 수 있다.
arr.sort((a, b) => {
  if (a[0] === b[0]) return a[1] - b[1]
  else return a[0] - b[0]
})

console.log('renew: ', arr)

 

2. 회의실 배정

방법:

끝시간이 가장 빠른 시간으로 정렬을 한다.

끝시간이 같을 경우는 

const fs = require('fs');
const input = fs.readFileSync("dev/stdin").toString().trim().split("\n");

input.shift()

const arr = input.map(item => item.split(" ").map(Number))

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

let et = 0;
let answer = 0
arr.forEach(item => {
  if (item[0] >= et) {
    answer++;
    et = item[1]
  }
})

console.log(answer)

 

3. 결혼식