[백준] 2470 두 용액 (골드5)

AI·2025년 9월 11일

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

14분 결과

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        // 산성 +, 알칼리 -
        // 두개만 합치니 => 투 포인터
        int n = Integer.parseInt(br.readLine());
        int[] a = new int[n];
        StringTokenizer st = new StringTokenizer(br.readLine());
        for(int i=0; i<n;i++){
            a[i] = Integer.parseInt(st.nextToken());
        }

        Arrays.sort(a);
        int[] ans = new int[2];

        int i = 0; int j = n-1; int min = Integer.MAX_VALUE;
        while (i<=j){
            if(min > Math.abs(a[i]+a[j])){
                min = Math.abs(a[i]+a[j]);
                ans[0] = a[i];
                ans[1] = a[j];
            }
            if(a[i]+a[j] <= 0)
                i++;
            else j--;
        }
        System.out.println(ans[0]+" "+ans[1]);
    }
}

추가로 7분 경과)
양수 2개 혹은 음수 2개가 0에 가까울 수도 있는 경우가 빠짐

if(Math.abs(a[i]) >= Math.abs(a[j]))
	i++;
else j--;
==
if(Math.abs(a[i+1]) >= Math.abs(a[j-1]))
	i++;
else j--;

해도 틀림

=>

if(Math.abs(a[i+1]+a[j]) >= Math.abs(a[i]+a[j-1]))
	j--;
else i++;

하니까 런타임 에러

=>
추가로 20분 경과

Math.abs를 쓰기 보다는 -를 넣어 시간 줄이기

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        // 산성 +, 알칼리 -
        // 두개만 합치니 => 투 포인터
        int n = Integer.parseInt(br.readLine());
        int[] a = new int[n];
        StringTokenizer st = new StringTokenizer(br.readLine());
        for(int i=0; i<n;i++){
            a[i] = Integer.parseInt(st.nextToken());
        }

        Arrays.sort(a);
        int[] ans = new int[2];

        int i = 0; int j = n-1; int min = Integer.MAX_VALUE;
        while (i<j){
            int sum = a[i]+a[j];
            int abs = sum >=0 ? sum:-sum;

            if(min > abs){
                min = abs;
                ans[0] = a[i];
                ans[1] = a[j];
                if(min == 0) break;
            }
            if(sum>0)
                j--;
            else i++;
        }
        System.out.println(ans[0]+" "+ans[1]);
    }
}

0개의 댓글