[백준/3649] 로봇 프로젝트 - JAVA

이지환·2023년 12월 19일

알고리즘(백준) 💻

목록 보기
8/80
post-thumbnail

📌 문제

알고리즘 분류 : 투포인터
난이도 : 골드5
출처 : 백준 - 로봇 프로젝트

🦧 문제 풀이 접근

크기가 n인 배열에 레고의 길이를 입력 받은 후 오름차순으로 정렬한다.
s와 e에 각각 0, n-1을 넣고 투포인터 알고리즘을 사용한다.

s번째 값과 e번째 값의 합이 x보다 크다면 e-1을 한다.
s번째 값과 e번째 값의 합이 x보다 작다면 e-1을 한다.
s번째 값과 e번째 값의 합이 x와 같으면 해당 값을 출력 한다.

💻 code

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        try {
            while(true) {//9_999_999
                int x = Integer.parseInt(br.readLine()) * 10_000_000;
                int n = Integer.parseInt(br.readLine());
                Integer[] arr = new Integer[n];
                for(int i=0;i<n;i++) {
                    arr[i] = Integer.parseInt(br.readLine());
                }
                Arrays.sort(arr);

                boolean check = false;
                int s=0, e=n-1;
                while(s<e) {
                    if(arr[s]+arr[e]==x) {
                        check = true;
                        break;
                    }
                    else if(arr[s]+arr[e]>x) {
                        e--;
                    }
                    else {
                        s++;
                    }
                }
                if(check)
                    sb.append("yes ").append(arr[s]).append(" ").append(arr[e]).append("\n");
                else
                    sb.append("danger").append("\n");
            }
        }
        catch (Exception e) {
            System.out.println(sb);
        }
    }
}

🥇 결과

🎓 느낀점

어렵지 않은 투포인터 문제다. 단위 변환에 주의하자.

profile
takeitEasy

0개의 댓글