본문 바로가기
컴퓨터 공학/백준

[백준] JAVA 자바 : 수 묶기 (1744번)

by kim-dev 2024. 5. 6.
반응형

 


 

현재 수가 양수인지 음수인지 나누어서 판단해야 한다.

 

현재 수가 양수인 경우, 1은 곱하지 않고 더해준다 2 이상의 수는 차례로 곱해서 합한다.
현재 수가 음수인 경우, -1 이하의 수는 모두 곱한 후 더해준다. 0은 음수로 포함시켜서, 가장 절댓값이 낮은 음수는 0과 곱해 0으로 만들어준다.

 

골드4 치고는 조금 쉽다고 느꼈던...? 문제였다.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.PriorityQueue;

public class TyingNumber {

    public static int stoi(String str) {
        return Integer.parseInt(str);
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        PriorityQueue<Integer> plusPQ = new PriorityQueue<>(Collections.reverseOrder());
        PriorityQueue<Integer> minusPQ = new PriorityQueue<>();
        
        int N = stoi(br.readLine()); // 배열 크기
        for (int i=0; i<N; i++) {
          int num = stoi(br.readLine());
          
          if (num > 0) {
            plusPQ.offer(num);
          } else {
            minusPQ.offer(num);
          }
        }

        int sum = 0;
        
        // 양수의 경우
        while(plusPQ.peek() != null) {
          Integer num1 = plusPQ.poll();
          Integer num2 = plusPQ.poll();
          //System.out.println(num1 + " " + num2);
          
          if (num2 == null) { // 하나밖에 안 남았다면
            sum += num1;
          } else if (num2 == 1) { // 하나가 1이라면
            sum += num1;
            plusPQ.offer(num2); // 1은 다시 집어 넣는다
          } else {
            sum += num1*num2;
          }
        }
        
        // 음수의 경우
        while(minusPQ.peek() != null) {
          Integer num1 = minusPQ.poll();
          Integer num2 = minusPQ.poll();
          
          if (num2 != null) {
            sum += num1*num2;
          } else {
            sum += num1;
          }
        }
        
        System.out.println(sum);
        br.close();
    }
}