https://www.acmicpc.net/problem/1244
문제
풀이
import java.io.*;
import java.util.*;
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());
int[] arr = new int[n+1];
StringTokenizer st = new StringTokenizer(br.readLine());
for(int i = 1; i <= n; i++){
arr[i] = Integer.parseInt(st.nextToken());
}
int t = Integer.parseInt(br.readLine());
for(int i = 0; i < t; i++){
st = new StringTokenizer(br.readLine());
int sex = Integer.parseInt(st.nextToken());
int index = Integer.parseInt(st.nextToken());
switch (sex){
case 1:
for(int j = index; j <= n; j += index){
change(arr, j);
}
break;
case 2:
change(arr, index);
int changeIndex = 1;
while(index - changeIndex >= 1 && index + changeIndex <= n){
if(arr[index - changeIndex] == arr[index + changeIndex]){
change(arr, index + changeIndex);
change(arr, index - changeIndex);
changeIndex++;
}else{
break;
}
}
break;
}
}
for(int i = 1; i <= n; i++){
System.out.print(arr[i] + " ");
if (i % 20 == 0) System.out.println();
}
}
public static void change(int[] arr, int index){
arr[index] = arr[index] == 0 ? 1: 0;
}
}
사용자에게 입력받은 성별에 따라 switch문을 사용해서 값을 변경해 준다.
값 변경은 3항 연산자를 통해 값이 0인 경우 1로, 1인 경우 0으로 바꾸는 메서드를 따로 제작했다.
for(int j = index; j <= n; j += index){
change(arr, j);
}
효율적인 처리를 위해 가장 고민했던 부분이다.
가장 초기에 생각했던 방법은 아래와 같다.
int mul = 1;
while(index*mul < n+1){
change(arr, index*mul);
mul++;
}
while(index*mul < n+1){
change(arr, index*mul);
mul++;
}
하지만 for문으로 처리하는 것이 더욱 효율적인 것 같다.
아직 for문을 쓸 때 시작 인덱스를 0,1로 하고, 연산자를 -- or ++하는 것에만 숙달된 느낌이 있다.
인덱스를 더욱 자유 자재로 다루는 연습을 해야 될 것 같다.
'문제 풀이 > 백준' 카테고리의 다른 글
[백준]1743번. 음식물 피하기(JAVA) (0) | 2024.04.08 |
---|---|
[백준]1138번. 한 줄로 서기 (1) | 2024.04.08 |
[백준]1406번. 에디터(JAVA) (0) | 2024.04.05 |
[백준]9375번. 패션왕 신해빈 (0) | 2024.04.04 |
[백준]4949번. 균형잡힌 세상(JAVA) (0) | 2024.04.04 |