๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 9037_The candy war

๋ฟŒ์•ผ._. 2024. 9. 2. 16:26
๋ฌธ์ œ(์ถœ์ฒ˜: https://www.acmicpc.net/problem/9037)

< The candy war >

 

๋ฌธ์ œ ํ’€์ด 

 

์‚ฌํƒ•์˜ ์ ˆ๋ฐ˜์„ ์˜ค๋ฅธ์ชฝ์— ๋„˜๊ฒจ์ฃผ๊ณ  ํ™€์ˆ˜๊ฐœ๋ผ๋ฉด 1์„ ๋”ํ•ด์ฃผ๋Š” ๊ณผ์ •์„ ์ „์ฒด ๊ฐ’์ด ๊ฐ™์•„์งˆ ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณตํ•œ๋‹ค.

 

 my solution (Java)

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

public class _9037_ { // The candy war

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

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

		for (int i = 0; i < T; i++) {
			int N = Integer.parseInt(bf.readLine());

			int cnt = 0;

			int arr[] = new int[N];
			int temp[] = new int[N];
			st = new StringTokenizer(bf.readLine());
			for (int j = 0; j < N; j++) {
				arr[j] = Integer.parseInt(st.nextToken());
				if (arr[j] % 2 != 0) {
					arr[j] += 1;
				}
			}

			boolean flag = false;
			for (int j = 0; j < N - 1; j++) {
				if (arr[j] != arr[j + 1]) {
					flag = true;
					break;
				}
			}
			if (!flag) {
				bw.write(cnt + "\n");
			} else {
				while (true) {
					flag = false;
					for (int j = 0; j < N; j++) {
						arr[j] /= 2;
						temp[j] = arr[j];
					}
					for (int j = 0; j < N; j++) {
						if (j + 1 == N) {
							arr[0] += temp[j];
							if (arr[0] % 2 != 0) {
								arr[0] += 1;
							}
						} else {
							arr[j + 1] += temp[j];
							if (arr[j + 1] % 2 != 0) {
								arr[j + 1] += 1;
							}
						}

					}
					cnt += 1;
					for (int j = 0; j < N - 1; j++) {
						if (arr[j] != arr[j + 1]) {
							flag = true;
							break;
						}
					}
					if (!flag) {
						bw.write(cnt + "\n");
						break;
					}
				}
			}
		}
		bw.flush();
	}
}
๋ณ€์ˆ˜)
T :  ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค ๊ฐœ์ˆ˜
N : ์•„์ด์˜ ์ธ์›์ˆ˜
cnt : ์ˆœํ™˜
arr : ๊ฐ ์•„์ด๊ฐ€ ๊ฐ€์ง€๋Š” ์‚ฌํƒ• ์ˆ˜
temp : ๊ฐ ์•„์ด์˜ ์‚ฌํƒ• ์ ˆ๋ฐ˜ ๊ฐ’
flag : ๋ชจ๋‘ ๊ฐ™์€ ์‚ฌํƒ•์ธ์ง€ ์—ฌ๋ถ€

 

ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค ๊ฐœ์ˆ˜๋ฅผ ์ž…๋ ฅ๋ฐ›๋Š”๋‹ค. ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค ์ˆ˜๋งŒํผ ๋‹ค์Œ ๊ณผ์ •์„ ๋ฐ˜๋ณตํ•œ๋‹ค.

 

1) ์•„์ด์˜ ์ธ์›์ˆ˜ ์ž…๋ ฅ๋ฐ›์Œ

2) ์•„์ด์˜ ์ธ์›์ˆ˜๋งŒํผ ์‚ฌํƒ•์˜ ๊ฐœ์ˆ˜ ์ž…๋ ฅ๋ฐ›์•„ arr์— ์ €์žฅ

3) arr์— ์ €์žฅ๋œ ๊ฐ’์ด ํ™€์ˆ˜๊ฐœ๋ผ๋ฉด 1 ๋”ํ•จ

4) ๋ชจ๋“  ์‚ฌํƒ•์˜ ๊ฐ’์ด ๊ฐ™์€ ๊ฐ’์ธ์ง€ ํ™•์ธ ํ›„ ๊ฐ™์€ ๊ฐ’์ด๋ผ๋ฉด 0 ์ถœ๋ ฅ ํ›„ 1)๋กœ ์ด๋™

5) ๋ชจ๋“  ์‚ฌํƒ•์˜ ๊ฐ’์ด ๊ฐ™์•„์งˆ ๋•Œ๊นŒ์ง€ ์‚ฌํƒ•์˜ ๊ฐœ์ˆ˜๋ฅผ ๋ฐ˜์œผ๋กœ ์ €์žฅ ํ›„ ์ ˆ๋ฐ˜์„ ์˜ค๋ฅธ์ชฝ์— ๋„˜๊ฒจ์คŒ. ๊ฐ€์ง„ ์‚ฌํƒ•์˜ ์ˆ˜๊ฐ€ ํ™€์ˆ˜๊ฐœ๋ผ๋ฉด 1 ๋”ํ•จ. ๋ชจ๋“  ์‚ฌํƒ•์˜ ๊ฐ’์ด ๊ฐ™์•„์กŒ๋‹ค๋ฉด cnt ์ถœ๋ ฅ ํ›„ 1)๋กœ ์ด๋™