Algorithm/Java
[백준/JAVA] 13305번: 블로그2
dbfl9911
2024. 7. 17. 17:14
반응형
https://www.acmicpc.net/problem/20365
- 정답 코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine()); // 문자 수
String colors = br.readLine(); // BBRBRBBR
// 각 색 카운트
int blue= 0;
int red = 0;
// 초기 색깔 설정
char currentColor = colors.charAt(0); // B
// 초기 색깔 기반으로 블록 수 증가
if(currentColor == 'B') {
blue++; // 1
}else {
red++;
}
// 색이 변경되는 지점 찾기
for(int i = 1; i < N; i++) {
if(colors.charAt(i) != currentColor) { // 색이 변경되는 지점
currentColor = colors.charAt(i);
if(currentColor == 'B') {
blue++;
}else{
red++;
}
}
}
// 작은값 기준으로 최소 작업 횟수 계산
int min = Math.min(blue, red) + 1;
System.out.println(min);
}
}
- 문제 풀이
1. 초기 블록 설정
if(currentColor == 'B') {
blue++; // 1
}else {
red++;
}
- 첫 번째 문제가 파란색이므로 blue를 1 증가시킵니다.
- 현재 blue는 1, red는 0입니다.
2. 색이 변경되는 지점 찾기
// 색이 변경되는 지점 찾기
for(int i = 1; i < N; i++) {
if(colors.charAt(i) != currentColor) { // 색이 변경되는 지점
currentColor = colors.charAt(i);
if(currentColor == 'B') {
blue++;
}else{
red++;
}
}
}
- i = 1, colors.charAt(1) = 'B': 현재 색과 동일하므로 넘어갑니다.
- i = 2, colors.charAt(2) = 'R': 색이 변경됨. currentColor = 'R', red++ → red = 1.
- i = 3, colors.charAt(3) = 'B': 색이 변경됨. currentColor = 'B', blue++ → blue = 2.
- i = 4, colors.charAt(4) = 'R': 색이 변경됨. currentColor = 'R', red++ → red = 2.
- i = 5, colors.charAt(5) = 'B': 색이 변경됨. currentColor = 'B', blue++ → blue = 3.
- i = 6, colors.charAt(6) = 'B': 현재 색과 동일하므로 넘어갑니다.
- i = 7, colors.charAt(7) = 'R': 색이 변경됨. currentColor = 'R', red++ → red = 3.
3. 최소 작업 횟수 계산
// 작은값 기준으로 최소 작업 횟수 계산
int min = Math.min(blue, red) + 1;
System.out.println(min);
- blue는 3, red도 3입니다.
- Math.min(3, 3) + 1 = 4.
- 따라서 최소 작업 횟수는 4입니다.
- 최소 작업 횟수는 이 값에 1을 더한 것입니다. 이유는 어느 한 색의 블록 전체를 먼저 칠하고, 그 사이의 다른 색의 블록을 한 번씩 칠하는 것이기 때문입니다.
반응형