티스토리 뷰

알고리즘/백준

[BAEKJOON]9037 The candy war

응애~ 개발자 2024. 1. 9. 02:45
728x90
반응형

문제 요약

  • 알고리즘 분류:  구현, 시뮬레이션
  • 난이도: Silver5
  • 문제내용:
    • 처음 각 사탕 홀 수 개이면 +1 해서 짝수개로 맞춘다.
    • 옆에 있는 학생에게 가지고 있는 사탕 반을 준다.
    • 모든 학생이 사탕 개수가 같게 할려면 몇번 순회 해야 하는지 각 케이스 마다 출력해라
  • 사이트: https://www.acmicpc.net/problem/9037
 

9037번: The candy war

입력은 표준입력(standard input)을 통해 받아들인다. 입력의 첫 줄에는 테스트 케이스의 개수 T가 주어진다. 각각의 테스트 케이스의 첫 줄에는 아이의 인원 N (1 ≤ N ≤ 10)이 주어지고 그 다음 줄에

www.acmicpc.net

문제풀이

 이번 문제는 간단한 1차원 배열 시뮬레이션을 구현 하는 문제이다. 이번 문제에서 구현 해야 할 것은 아래의 3개만 구현 하면 된다.

1. 사탕 짝수개로 맞추는 것

2. 모든 학생 사탕 개수가 같게 하는것

3. 옆에 있는 학생에게 사탕 반개씩 주는것

 

1. 사탕 짝수개로 맞추는 것

 문제에서 사탕 홀수를 짝수를 맞추는 것이다. 아래 코드처럼 구현 하면 된다.

Python

def checkCandy(candies):
    for i in range(len(candies)):
        candies[i] = candies[i] + 1 if candies[i] % 2 == 1 else candies[i]
    return candies

Java

public static int[] checkCandy(int[] candies){

    for(int i = 0; i < candies.length; i++){
        // 캔디 개수가 홀 수이면 1개 추가한다.
        if(candies[i] % 2 == 1){
            candies[i]++;
        }
    }

    return candies;
}

 

2. 모든 학생 사탕 개수가 같게 하는것

Python

def isSameCandy(candies):
    for candy in candies:
        if candy != candies[0]:
            return False
    return True

Java

public static boolean isSameCandy(int[] candies){
    for(int candy : candies){
        // 모든 사탕은 같아야 하기 때문에
        if (candy != candies[0]){
            return false;
        }
    }
    return true;
}

 

3. 옆에 있는 학생에게 사탕 반개씩 주는것

Python

def roundCandy(candies):
    length = len(candies)
    newCandies = [0 for _ in range(length)]
    for i in range(length):
        newCandies[i] = candies[i] // 2 + candies[(i - 1) % length] // 2
    return newCandies

Java

public static int[] roundCandy(int[] candies){

    int len = candies.length;

    int[] newCandies = new int[len];

    for(int i = 0; i < len; i++){
        newCandies[(i + 1) % len] = candies[i] / 2 + candies[(i + 1) % len] / 2; // 맨끝에 있는 학생은 맨 처음의 한생으로 줘야 하기 때문에 뒤에 길이 만 큼 나눈 나머지로 해야 한다.
    }
    return newCandies;
}

 

 위에 3개를 구현하고 끝나면 카운터를 증가하는 식으로 구현만 하면 쉽게 풀수 있다. 전제 코드는 아래 보면 된다.

 

 

Code

Python

# 사탕 짝수개 맞추기
def checkCandy(candies):
    for i in range(len(candies)):
        candies[i] = candies[i] + 1 if candies[i] % 2 == 1 else candies[i]
    return candies

# 모든 사탕 같은지 확인 하는 메소드
def isSameCandy(candies):
    for candy in candies:
        if candy != candies[0]:
            return False
    return True

# 사탕 순회
def roundCandy(candies):
    length = len(candies)
    newCandies = [0 for _ in range(length)]
    for i in range(length):
        newCandies[i] = candies[i] // 2 + candies[(i - 1) % length] // 2
    return newCandies

for _ in range(int(input())):
    N = int(input())
    C = list(map(int, input().split()))
    count = 0
    while True:
        C = checkCandy(C)
        if isSameCandy(C):
            break
        C = roundCandy(C)
        count += 1
    print(count)

Java

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));
		StringTokenizer st;

		int T = Integer.parseInt(br.readLine());
		int N, count;
		int[] C;

		for(int i = 0; i < T; i++){
			N = Integer.parseInt(br.readLine());
			C = new int[N];
			st = new StringTokenizer(br.readLine());
			for(int j = 0; j < N; j++){
				C[j] = Integer.parseInt(st.nextToken());
			}

			count = 0;
			while (true){
				C = checkCandy(C);
				if(isSameCandy(C)){
					break;
				}
				C = roundCandy(C);
				count++;

			}

			System.out.println(count);
		}

	}

	/*
	 * 사탕 짝수개 맞추는 작업
	 */
	public static int[] checkCandy(int[] candies){

		for(int i = 0; i < candies.length; i++){
			// 캔디 개수가 홀 수이면 1개 추가한다.
			if(candies[i] % 2 == 1){
				candies[i]++;
			}
		}

		return candies;
	}

	/*
	* 사탕 개수 같은지 확인하는 메소드
	 */
	public static boolean isSameCandy(int[] candies){
		for(int candy : candies){
			// 모든 사탕은 같아야 하기 때문에
			if (candy != candies[0]){
				return false;
			}
		}
		return true;
	}

	/*
	 * 사탕 순환
	 */
	public static int[] roundCandy(int[] candies){

		int len = candies.length;

		int[] newCandies = new int[len];

		for(int i = 0; i < len; i++){
			newCandies[(i + 1) % len] = candies[i] / 2 + candies[(i + 1) % len] / 2; // 맨끝에 있는 학생은 맨 처음의 한생으로 줘야 하기 때문에 뒤에 길이 만 큼 나눈 나머지로 해야 한다.
		}
		return newCandies;
	}

}
728x90
반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함