๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 2036_์ˆ˜์—ด์˜ ์ ์ˆ˜

๋ฟŒ์•ผ._. 2023. 6. 29. 10:02

Gold IV

๋ฌธ์ œ(์ถœ์ฒ˜: https://www.acmicpc.net/problem/2036)

< ์ˆ˜์—ด์˜ ์ ์ˆ˜ >

 

๋ฌธ์ œ ํ’€์ด & ์ƒ๊ฐ

 

๋‹จ์ˆœ ์กฐ๊ฑด ๋ถ„๊ธฐ๋ฅผ ํ™œ์šฉํ•ด์„œ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ์˜€๋‹ค. (0๊ณผ 1์ด ์กด์žฌํ•  ๋•Œ ์กฐ๊ฑด ๋ถ„๊ธฐ๋ฅผ ๋†“์น˜์ง€ ์•Š์•„์•ผ ํ•œ๋‹ค.)

 

๋ฐ˜๋ก€ ์กฐ๊ฑด

1) 1, 3์ด ์žˆ์„ ๊ฒฝ์šฐ 1*3 < 1+3์ด๋‹ค.

2) -8,0๊ณผ ๊ฐ™์ด 0์ด ์žˆ์œผ๋ฉฐ ์Œ์ˆ˜๊ฐ€ 1๊ฐœ ์žˆ๋‹ค๋ฉด -8*0 > -8+0์ด๋‹ค.

 

๋˜ํ•œ, 1,000,000์ด ๋„˜์ง€ ์•Š๋Š” ์ •์ˆ˜๊ฐ€ ์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง€๋ฏ€๋กœ int ๋ฒ”์œ„๊ฐ€ ๋ฒ—์–ด๋‚˜๋ฏ€๋กœ longํ˜•์„ ์‚ฌ์šฉํ•ด์•ผ ํ•œ๋‹ค.

 

 my solution (Java)

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

public class _2036_ { // ์ˆ˜์—ด์˜ ์ ์ˆ˜

	public static void main(String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));

		int n = Integer.parseInt(bf.readLine());

		long arr[] = new long[n];
		int neg = 0, zero = 0;
		for (int i = 0; i < n; i++) {
			arr[i] = Long.parseLong(bf.readLine());
			if (arr[i] < 0)
				neg += 1;
			else if (arr[i] == 0)
				zero += 1;
		}

		Arrays.sort(arr);

		long result = 0;
		int idx = 0, pos = n - neg - zero;
		while (idx < n) {
			if (neg > 0) {
				if (neg == 1) {
					if (zero > 0) {
						zero -= 1;
						neg -= 1;
						idx += 2;
					} else {
						result += arr[idx];
						neg -= 1;
						idx += 1;
					}
				} else {
					result += arr[idx] * arr[idx + 1];
					idx += 2;
					neg -= 2;
				}
			} else if (zero > 0) {
				idx += zero;
				zero = 0;
			} else if (pos > 0) {
				if (arr[idx] == 1) {
					result += arr[idx];
					idx += 1;
					pos -= 1;
				} else if (pos % 2 == 0) {
					result += arr[idx] * arr[idx + 1];
					idx += 2;
					pos -= 2;
				} else {
					result += arr[idx];
					pos -= 1;
					idx += 1;
				}
			}
		}
		System.out.println(result);
	}
}

 

Main

๋ณ€์ˆ˜)
n : ์ˆ˜์—ด์˜ ํฌ๊ธฐ
arr : ์ˆ˜์—ด ์ €์žฅ
neg, zero, pos: ์Œ์ˆ˜, 0, ์–‘์ˆ˜ ๊ฐœ์ˆ˜
result: ์ตœ๋Œ€ ์ •์ˆ˜

 

- ์ˆ˜์—ด์˜ ํฌ๊ธฐ (n) ์ž…๋ ฅ

- ์ˆ˜์—ด ์ž…๋ ฅ๋ฐ›์€ ํ›„ ์ €์žฅํ•œ ๋ฐฐ์—ด ์ •๋ ฌ

 

์กฐ๊ฑด)

1) -8, 0๊ณผ ๊ฐ™์ด ์Œ์ˆ˜๊ฐ€ 1๊ฐœ ์žˆ์œผ๋ฉฐ 0๋„ ์กด์žฌํ•œ๋‹ค๋ฉด ๋‘ ์ •์ˆ˜ ์ œ๊ฑฐ, 0์ด ์—†๋‹ค๋ฉด ํ•œ ์ •์ˆ˜ ์ œ๊ฑฐ

2) -8, -5์™€ ๊ฐ™์ด ์Œ์ˆ˜๊ฐ€ 1๊ฐœ๋ณด๋‹ค ๋งŽ๋‹ค๋ฉด ๋‘ ์ •์ˆ˜ ๊ณฑํ•˜๋ฉด ์–‘์ˆ˜๊ฐ€ ๋˜๋ฏ€๋กœ ๋‘ ์ •์ˆ˜ ์ œ๊ฑฐ

3) 0์ด ์—ฌ๋Ÿฌ ๊ฐœ ์žˆ๋‹ค๋ฉด ๊ณฑํ•˜๊ฑฐ๋‚˜ ๋”ํ•˜๊ฑฐ๋‚˜ 0์ด๋ฏ€๋กœ pass

4) ์–‘์ˆ˜ ์ค‘์—์„œ 1, 3๊ณผ ๊ฐ™์ด 1์ด ์žˆ๋‹ค๋ฉด 1*3 < 1+3 ์ด๋ฏ€๋กœ 1์ด ์žˆ์„ ๋•Œ๋Š” ํ•œ ์ •์ˆ˜๋งŒ ์ œ๊ฑฐํ•˜์—ฌ 1 ์ œ๊ฑฐํ•˜๊ธฐ

5) 1์„ ๋‹ค ์ œ๊ฑฐํ•œ ํ›„ ์–‘์ˆ˜๊ฐ€ ์ง์ˆ˜๊ฐœ ์žˆ๋‹ค๋ฉด ๋‘ ์ •์ˆ˜ ์ œ๊ฑฐ but  2, 3, 5์™€ ๊ฐ™์ด ํ™€์ˆ˜๊ฐœ ์žˆ๋‹ค๋ฉด ์ž‘์€ ์ˆ˜๋ฅผ ํ•˜๋‚˜ ์ œ๊ฑฐํ•˜๊ณ  ๋‚˜๋จธ์ง€๋ฅผ ๋‘ ๊ฐœ์”ฉ ๊ณฑํ•˜๋Š” ๊ฒƒ์ด ํฐ ์ˆ˜๋ฅผ ์–ป์„ ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ ํ•œ ์ •์ˆ˜ ์ œ๊ฑฐ

 

- ์ตœ๋Œ€ ์ ์ˆ˜(result) ์ถœ๋ ฅ