๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 12931_๋‘ ๋ฐฐ ๋”ํ•˜๊ธฐ

๋ฟŒ์•ผ._. 2024. 3. 18. 21:28

Gold V

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

< ๋‘ ๋ฐฐ ๋”ํ•˜๊ธฐ >

 

๋ฌธ์ œ ํ’€์ด 

 

๋ฐฐ์—ด B๋ฅผ ์ด์šฉํ•˜์—ฌ

1) ๋ฐฐ์—ด์— ์žˆ๋Š” ๊ฐ’ ํ•˜๋‚˜๋ฅผ 1 ๊ฐ์†Œ์‹œํ‚ค๊ธฐ

2) ๋ฐฐ์—ด์— ์žˆ๋Š” ๋ชจ๋“  ๊ฐ’์„ 2๋กœ ๋‚˜๋ˆ„๊ธฐ

๋‘ ๊ฐ€์ง€ ์—ฐ์‚ฐ์„ ์ˆ˜ํ–‰ํ•˜์—ฌ ๋ชจ๋“  ๊ฐ’์ด 0์ธ ๋ฐฐ์—ด์„ ๋งŒ๋“ ๋‹ค.

 

 my solution (Java)

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

public class _12931_ { // ๋‘ ๋ฐฐ ๋”ํ•˜๊ธฐ

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

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

		int arr[] = new int[n];
		st = new StringTokenizer(bf.readLine());
		for (int i = 0; i < n; i++) {
			arr[i] = Integer.parseInt(st.nextToken());
		}

		int answer = 0;
		int zero = 0;
		boolean flag = false;

		while (zero != n) {
			zero = 0;
			flag = false;

			for (int i = 0; i < n; i++) {
				if (arr[i] == 0) {
					zero += 1;
				}
			}
			if (zero == n) {
				break;
			}
			for (int i = 0; i < n; i++) {
				if (arr[i] % 2 == 1) {
					arr[i] -= 1;
					answer += 1;
				}
			}
			for (int i = 0; i < n; i++) {
				if (arr[i] != 0 && arr[i] % 2 == 0) {
					if (!flag) {
						flag = true;
						answer += 1;
					}
					arr[i] /= 2;
				}
			}
		}
		System.out.println(answer);
	}
}
๋ณ€์ˆ˜)
n : ๋ฐฐ์—ด์˜ ํฌ๊ธฐ
arr : ๋ฐฐ์—ด B ๊ฐ’
answer : ์ตœ์†Œ ์—ฐ์‚ฐ ํšŸ์ˆ˜
zero : ๋ฐฐ์—ด์˜ ๊ฐ’์ด 0์ธ ๊ฐœ์ˆ˜

 

๋ฐฐ์—ด์˜ ํฌ๊ธฐ๋ฅผ ์ž…๋ ฅ๋ฐ›๋Š”๋‹ค. ๋ฐฐ์—ด์˜ ํฌ๊ธฐ๋งŒํผ ๋ฐฐ์—ด B์— ๋“ค์–ด์žˆ๋Š” ์›์†Œ๋ฅผ ์ž…๋ ฅ๋ฐ›์•„ ์ €์žฅํ•œ๋‹ค. ๋ฐฐ์—ด์˜ ๋ชจ๋“  ๊ฐ’์ด 0์ผ ๋•Œ๊นŒ์ง€ ๋‹ค์Œ ๊ณผ์ •์„ ๋ฐ˜๋ณตํ•œ๋‹ค.

1) ๋ฐฐ์—ด ์ „์ฒด๋ฅผ ํƒ์ƒ‰ํ•˜๋ฉฐ ๋ชจ๋“  ๊ฐ’์ด 0์ธ์ง€ ํ™•์ธํ•œ๋‹ค. 0์ด๋ผ๋ฉด ์ข…๋ฃŒ

2) 2๋กœ ๋‚˜๋ˆ„์–ด ๋–จ์–ด์ง€์ง€ ์•Š๋Š”๋‹ค๋ฉด 1์„ ๊ฐ์†Œ์‹œํ‚ค๋ฉฐ answer์„ 1 ์ฆ๊ฐ€์‹œํ‚จ๋‹ค.

3) ๋ฐฐ์—ด์— ์žˆ๋Š” ๋ชจ๋“  ๊ฐ’์„ 2๋กœ ๋‚˜๋ˆ„๋ฉฐ answer์„ 1 ์ฆ๊ฐ€์‹œํ‚จ๋‹ค.

์ตœ์†Œ ์—ฐ์‚ฐ ํšŸ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.