백준 2473 세 용액 js

2022. 1. 13. 19:57·Nodejs로 알고리즘 박살내기

 

 

2473번: 세 용액

첫째 줄에는 전체 용액의 수 N이 입력된다. N은 3 이상 5,000 이하의 정수이다. 둘째 줄에는 용액의 특성값을 나타내는 N개의 정수가 빈칸을 사이에 두고 주어진다. 이 수들은 모두 -1,000,000,000 이상

www.acmicpc.net

풀이

두 용액을 먼저 선택하고 두 용액의 합한 값과 나머지 배열에서 하나의 값을 더했을 때 0에 가까운 값을 찾는 이분 탐색을 진행하였습니다.

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

let N;
let input = [];
let min = 3000000000;

function solution() {
  let result = [];

  for(let i = 0; i < N - 2; i++) {
    for(let j = i + 1; j < N - 1; j++) {
      // 두 용액을 num1, num2로 지정
      let num1 = input[i];
      let num2 = input[j];
      
      // 나머지 배열인 j + 1 index부터 이분 탐색 시작
      let l = j + 1;
      let r = input.length - 1;

      while(l <= r) {
        let mid = (l + r) / 2 >> 0;
        let total = num1 + num2 + input[mid];

        if(min > Math.abs(total)) {
          min = Math.abs(total);
          result = [num1, num2, input[mid]];
        }

        if(total === 0) {
          return result;
        } else if(total > 0) {
          r = mid - 1;
        } else {
          l = mid + 1;
        }
      }
    }
  }

  return result;
}

rl.on('line', function (line) {
  if(!N) {
    N = +line;
  } else {
    input = line.split(' ').map(n => +n);
    input.sort((a, b) => a - b);
    
    let answer = solution()
    console.log(answer.join(' '));
    rl.close();
  }
})

위와 같이 단순하게 풀었더니 O(N^2logN)으로 그다지 효율적이지 않아 다른 사람들 코드를 참고하여 보았더니 하나의 값을 먼저 지정하고 나머지 두 개의 용액을 투 포인터 방식으로 총합이 0에 가까운 값을 찾는 솔루션이였습니다.

따라서 참고하여 O(N^2)의 시간 복잡도를 갖는 방식으로 수정해보겠습니다.

최종 코드

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

let N;
let input = [];
let min = 3000000000;

function solution() {
  let result = [];

  for(let i = 0; i < N - 2; i++) {
    let l = i + 1;
    let r = N - 1;

    while(l < r) {
      let total = input[i] + input[l] + input[r];

      if(min > Math.abs(total)) {
        min = Math.abs(total);
        result = [input[i], input[l], input[r]];
      }

      if(total > 0) {
        r -= 1;
      } else {
        l += 1;
      }
    }
  }

  return result;
}

rl.on('line', function (line) {
  if(!N) {
    N = +line;
  } else {
    input = line.split(' ').map(n => +n);
    input.sort((a, b) => a - b);
    
    let answer = solution()
    console.log(answer.join(' '));
    rl.close();
  }
})

오늘도 하나 배워갑니다.

저작자표시 (새창열림)

'Nodejs로 알고리즘 박살내기' 카테고리의 다른 글

프로그래머스 LV.4 지형 이동 js  (1) 2022.03.11
백준 4386 별자리 만들기 js  (0) 2022.03.09
백준 1738 골목길 js  (0) 2022.03.09
백준 2493 탑 js  (0) 2022.01.15
백준 3020 개똥벌레  (0) 2022.01.12
'Nodejs로 알고리즘 박살내기' 카테고리의 다른 글
  • 백준 4386 별자리 만들기 js
  • 백준 1738 골목길 js
  • 백준 2493 탑 js
  • 백준 3020 개똥벌레
heesu
heesu
개발하면서 겪었던 경험을 공유합니다.
  • heesu
    heesu dev
    heesu
  • 전체
    오늘
    어제
    • 분류 전체보기
      • Nodejs로 알고리즘 박살내기
      • 사이드 프로젝트
        • Bitfolio
      • React Native
      • Etc
      • HTML
      • NextJS
      • Javascript
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    redux-persist
    우선순위 큐
    dfs
    Nodejs
    union-find
    벨만포드 알고리즘
    asyncstorage
    최소 스패닝
    cleancode
    react-native
    알고리즘
    BFS
    크루스칼 알고리즘
    letsencrypt
    UnionFind
    시맨틱 태그
    Dijkstra
    JavaScript
    certbot
    React Native
    Animated
    정렬
    크루스칼
    lv4
    학습
    부분합
    프로그래머스
    완전 탐색
    백준
    투 포인터
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
heesu
백준 2473 세 용액 js
상단으로

티스토리툴바