1 분 소요



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



🔍 문제 풀이

문제 도식화

1244 도식화

출력 형식

이 문제는 정답률이 낮은 편인데, 출력 형식 실수가 원인인 경우가 많은 것 같다.

정답을 출력할 때 스위치 상태를 20개마다 줄 바꿈해야 하니 주의하자!

for (int i = 1; i <= n; i++) {
    System.out.print(switches[i] + " ");
    if (i % 20 == 0) System.out.println(); // 20개마다 줄바꿈
}


xor 연산으로 쉽게 상태 토글이 가능하다.

static void toggle(int x){
    switches[x] ^= 1; // xor 연산
}



💻 전체 코드

import java.io.*;
import java.util.*;

public class Main {
    static int[] switches;
    static int n;

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

        n = Integer.parseInt(br.readLine()); // 스위치 개수

        // 스위치 상태
        switches = new int[n+1];
        StringTokenizer st = new StringTokenizer(br.readLine());
        for(int i=1; i<=n; i++){
            switches[i] = Integer.parseInt(st.nextToken());
        }

        int sc = Integer.parseInt(br.readLine()); // 학생 수
        while(sc --> 0){
            st = new StringTokenizer(br.readLine());
            int sex = Integer.parseInt(st.nextToken()); // 성별
            int x = Integer.parseInt(st.nextToken()); // 받은 수

            solved(sex, x);
        }

        for(int i=1; i<=n; i++){
            System.out.print(switches[i] + " ");
            if(i % 20 == 0) System.out.println(); // 주의
        }

    }
    static void solved(int sex, int x){
        // 남자면 스위치 상태 바꿈
        if(sex == 1) {
            for(int i=1; i<=n; i++){
                if(i%x==0){
                    toggle(i);
                }
            }
        }

        // 여자면 대칭 상태 확인 후 상태 바꿈
        if(sex == 2) {
            toggle(x);

            int left = x-1;
            int right = x+1;

            // 좌우 대칭 찾기
            // 배열 범위 안에 있고 왼쪽과 오른쪽 같을 때만
            while (left >= 1 && right <= n && switches[left] == switches[right]) {
                toggle(left);
                toggle(right);
                left--;
                right++;
            }
        }
    }

    static void toggle(int x){
        switches[x] ^= 1; // xor 연산
    }
}


카테고리:

업데이트:

댓글남기기