문제 풀이 날짜: 2023.08.01
포스트 작성일: 2023.08.01
* 학습 목적으로 작성하는 글입니다. 풀이가 정석적이지 못할 수도 있습니다.
문제 출처
백준 온라인 저지 1244번: 스위치 켜고 끄기 (실버4)
키워드
구현
풀이 접근법
- 문제에서 주어진 스위치 번호와 배열 인덱스가 다르므로 주의한다.
- 주어진 조건에 맞게 스위치를 끄고 켠다. 0을 1로 바꾸고 1을 0으로 바꾸는 부분은 삼항연산자를 이용한다.
- 인덱스 0번을 사용하지 않으므로 반복문 첨자를 초기화할 때 주의한다. 특히 여학생이 스위치를 누르는 부분을 구현할 때, 대칭되는 스위치를 찾다가 엉뚱한 스위치를 눌러버리는 오류가 발생할 수 있다.
코드
import java.io.*;
public class boj1244 {
private static int[] switches;
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int switchNum = Integer.parseInt(br.readLine());
switches = new int[switchNum + 1]; //0은 제외
String[] temp = br.readLine().split(" ");
for(int i = 1; i <= switchNum; i++) {
switches[i] = Integer.parseInt(temp[i - 1]);
}
int commandNum = Integer.parseInt(br.readLine());
for(int i = 0; i < commandNum; i++) {
temp = br.readLine().split(" ");
int command = Integer.parseInt(temp[0]);
int key = Integer.parseInt(temp[1]);
modifySwitches(command, key);
}
StringBuilder sb = new StringBuilder();
for(int i = 1; i <= switchNum; i++) {
sb.append(switches[i]).append(" ");
if(i % 20 == 0) {
sb.append("\n");
}
}
System.out.println(sb);
}
private static void modifySwitches(int command, int key) {
if(command == 1) {
for(int i = 1; i < switches.length; i++) {
if(i % key == 0) { //스위치 번호가 자기가 받은 수의 배수라면
switches[i] = (switches[i] == 0) ? 1 : 0;
}
}
} else if(command == 2) {
switches[key] = (switches[key] == 0) ? 1 : 0;
//key - i > 0 에서 등호가 들어가면 안 된다. (그걸 지워서 맞음)
//만약 0번 인덱스와 그것과 대칭되는 위치의 수가 대칭이라면
//굳이 조작하지 않아도 되는 스위치까지 조작하게 된다.
for(int i = 1; key - i > 0 && key + i < switches.length; i++) {
if(switches[key - i] == switches[key + i]) {
switches[key - i] = (switches[key - i] == 0) ? 1 : 0;
switches[key + i] = (switches[key + i] == 0) ? 1 : 0;
}
else break;
}
}
}
}
git 링크
(git 링크 첨부)
'Study > Problem Solving' 카테고리의 다른 글
[백준 / Java] 2961번: 도영이가 만든 맛있는 음식 (실버2) (0) | 2023.08.03 |
---|---|
[백준 / Java] 2839번: 설탕 배달 (실버4) (0) | 2023.08.02 |
[SWEA / Java] 1210번: Ladder1 (D4) (0) | 2023.08.01 |
[백준 / Java] 10799번: 쇠막대기 (실버2) (0) | 2023.07.27 |
[SWEA / Java] 4047번: 영준이의 카드 카운팅 (D3) (0) | 2023.07.27 |