체크박스
in Algorithm on SW Expert Academy
백준 [34545] 체크박스
소스코드
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int[] currentStatus = new int[N];
int[] targetStatus = new int[N];
// 현재 상태를 입력받으며, 전체 선택이거나 전체 해제 상태인지 확인
boolean isAllCheck = true;
boolean isAllUncheck = true;
for (int i = 0; i < N; i++) {
currentStatus[i] = sc.nextInt();
if (currentStatus[i] == 0) {
isAllCheck = false;
}
if (currentStatus[i] == 1) {
isAllUncheck = false;
}
}
int answer = 0;
// 목표 상태를 입력받으며, 한개씩 변경하는 경우 몇번의 조작이 필요한지 확인 (방법1)
int diffCnt = 0;
for (int i = 0; i < N; i++) {
targetStatus[i] = sc.nextInt();
if (currentStatus[i] != targetStatus[i]) {
diffCnt++;
}
}
answer = diffCnt;
if (answer == 0) {
System.out.println(answer);
return;
}
// 전체 on 후, 하나씩 변경 (방법2)
int diffCntAfterAllChk = 0;
if (!isAllCheck) {
diffCntAfterAllChk++;
}
diffCntAfterAllChk += countDiffStatus(N, targetStatus, 1);
answer = Math.min(answer, diffCntAfterAllChk);
// 전체 off 후, 하나씩 변경 (방법3)
int diffCntAfterAllUnchk = 0;
if (!isAllUncheck) {
if (!isAllCheck) { // 토글 상태라면 전체 체크 상태로 만든 후 전체 해제
diffCntAfterAllUnchk += 2;
} else { // 이미 전체 체크 상태라면 바로 해제
diffCntAfterAllUnchk += 1;
}
}
diffCntAfterAllUnchk += countDiffStatus(N, targetStatus, 0);
answer = Math.min(answer, diffCntAfterAllUnchk);
System.out.println(answer);
}
private static int countDiffStatus(int N, int[] targetStatus, int compareStatus) {
int diffCnt = 0;
for (int i = 0; i < N; i++) {
if (compareStatus != targetStatus[i]) {
diffCnt++;
}
}
return diffCnt;
}
}