Shiny Sky Blue Star

백준 문제 풀이/백준 (JAVA)

JAVA 백준 1244 스위치 켜고 끄기

gamja00 2024. 7. 9. 01:33

 

https://www.acmicpc.net/problem/1244


문제

  1. 첫째 줄에 스위치의 개수 N ( 1 <= N <= 100 ) 입력.
  2. 둘째 줄에 각 스위치의 상태 N개 입력.
  3. 셋째 줄에 학생 수 M ( 1 <= M <= 100 ) 입력.
  4. 넷째 줄부터 M개의 줄에 한 줄에 학생의 성별( 남 - 1, 여 - 2 )과 학생이 받은 수를 공백으로 구분하여 입력.
  5. 켜진 스위치는 1, 꺼진 스위치는 0.
  6. 학생이 남자면 배수번 스위치 상태를 반전시킨다.
  7. 학생이 여자면 받은 수를 기준으로 하여 좌우 반전했을 때 동일하지 않은 곳까지 스위치 상태를 반전시킨다.
  8. 1번 스위치에서 시작하며 한 줄에 20개씩 공백으로 구분하여 출력. (21번 스위치부터는 둘째 줄에 출력)

 

 

최종 코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();

        int N = Integer.parseInt(br.readLine());

        int[] list = new int[N];

        StringTokenizer st = new StringTokenizer(br.readLine());

        for (int i = 0; i < N; i++) {
            list[i] = Integer.parseInt(st.nextToken());
        }


        int student = Integer.parseInt(br.readLine());

        for (int i = 0; i < student; i++) {
            st = new StringTokenizer(br.readLine());

            int gender = Integer.parseInt(st.nextToken());
            int num = Integer.parseInt(st.nextToken());

            if (gender == 1) {
                int j = num - 1;

                while (j < N) {
                    if (list[j] == 0) {
                        list[j] = 1;
                    } else {
                        list[j] = 0;
                    }
                    j += num;
                }
            } else {
                int count = 0;
                while ((0 <= num - count - 1 && num + count - 1 < N)
                        && (list[num - count - 1] == list[num + count - 1])) {
                    count++;
                }

                for (int j = num - count; j < num - 1 + count; j++) {
                    if (list[j] == 0) {
                        list[j] = 1;
                    } else {
                        list[j] = 0;
                    }
                }
            }
        }

        int count = 0;
        for (int n : list) {
            sb.append(n).append(" ");
            count++;
            if(count==20){
                sb.append("\n");
                count=0;
            }
        }

        System.out.print(sb);
    }
}