그리디 알고리즘

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. 결혼식

'알고리즘 풀이' 카테고리의 다른 글

정렬  (0) 2022.08.04
다이나믹 프로그래밍  (0) 2022.07.02
Node.js로 백준문제 테스트하기(with Replit)  (0) 2022.06.26
BFS 넓이 우선 탐색  (0) 2022.06.18
그래프 정렬  (0) 2022.06.11
'알고리즘 풀이' 카테고리의 다른 글
  • 정렬
  • 다이나믹 프로그래밍
  • Node.js로 백준문제 테스트하기(with Replit)
  • BFS 넓이 우선 탐색
JoyYellow
JoyYellow
  • JoyYellow
    JoyYellow
    JoyYellow
  • 전체
    오늘
    어제
    • 분류 전체보기 (128)
      • Vue (7)
      • React (10)
      • 알고리즘 풀이 (29)
      • 타입스크립트 (2)
      • Microsoft (4)
      • TIL(Today I Learned) (16)
      • Devops (4)
      • CS(Computer Science) (2)
      • Spring (1)
      • Incomplete (0)
      • JS소스모듈 (10)
      • TDD (2)
      • 스프링부트 (0)
      • CSS (8)
      • Next.js (0)
  • 블로그 메뉴

    • 홈
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    개발자북클럽
    노개북
    노마드코더
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
JoyYellow
그리디 알고리즘
상단으로

티스토리툴바