[백준]공 포장하기

백준 온라인 저지

공 포장하기

링크 : 문제 바로가기

package Baekjoon;

import java.util.*;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int r=sc.nextInt();
		int g=sc.nextInt();
		int b=sc.nextInt();
		int result=0;
		int rA=r/3;
		int rB=r%3;
		int gA=g/3;
		int gB=g%3;
		int bA=b/3;
		int bB=b%3;
		int aaa=Math.max(rB, gB);
		int maxB=Math.max(aaa, bB);
		result+=rA;
		result+=gA;
		result+=bA;
		result+=maxB;
		System.out.println(result);
		
		
	}
}

틀린결과로 나오는데 어는 부분이 잘못되고 반례는 무엇인지 모르겠다.

해결

package Baekjoon;

import java.util.*;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int r=sc.nextInt();
		int g=sc.nextInt();
		int b=sc.nextInt();
		int result=0;
		int rA=r/3;
		int rB=r%3;
		int cnt=0;
		if (rB==0) {
			cnt+=1;
		}
		int gA=g/3;
		int gB=g%3;
		if (gB==0) {
			cnt+=1;
		}
		int bA=b/3;
		int bB=b%3;
		if (bB==0) {
			cnt+=1;
		}
		int aaa=Math.max(rB, gB);
		int maxB=Math.max(aaa, bB);
		if (cnt==2) {
			maxB=1;
		}
		result+=rA;
		result+=gA;
		result+=bA;
		result+=maxB;
		System.out.println(result);
		
		
	}
}

원래 코드에서는 같은 종류를 3개씩 묶고 남은 나머지들을 모아서 처리했다. 예를 들어 나머지가 ‘2개 1개 1개’라면 3가지 중 가장 큰 수를 찾아 그 수만큼 박스를 쓴다고 생각했다. 하지만 ‘2개 0개 0개’의 경우 박스를 2개쓰지 않고 박스를 1개만 쓰고 처리가 가능했다. 그래서 이렇게 나머지가 0개인 종류가 2가지일 경우를 따로 빼서 처리해주었더니 해결되었다.

알고리즘 : 그리디

results matching ""

    No results matching ""