본문 바로가기
Problem Solving/Baekjoon

[백준] 28464 Potato - Greedy / Java

by graycode 2023. 9. 24.

 문제 링크

 

28464번: Potato

감자튀김을 좋아하는 박 모 씨와 다르게, 성우는 감자튀김을 그렇게 좋아하지는 않는다. 어느 날 박 모 씨와 성우는 수많은 감자튀김을 받게 되었고, 이를 나누어 가지기로 했다. 책상 위에 $N$개

www.acmicpc.net

 

 풀이 코드

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;

public class Main {

    public static void main(String[] args) throws IOException {
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        int n = read();

        int[] arr = new int[n];
        while (n-- > 0) arr[n] = read();

        Arrays.sort(arr);

        int a = 0, b = 0, s = 0, e = arr.length - 1, l = arr.length / 2;
        if (arr.length % 2 != 0) b += arr[l];

        while (s < l) {
            a += arr[s++];
            b += arr[e--];
        }

        bw.write(a + " " + b);
        bw.flush();
    }

    private static int read() throws IOException {
        int c, n = System.in.read() & 15;
        while ((c = System.in.read()) > 32) n = (n << 3) + (n << 1) + (c & 15);

        return n;
    }

}

댓글