chae._.chae

[Algorithm] 백준 #1244 스위치 켜고 끄기 본문

파이썬 알고리즘/BOJ

[Algorithm] 백준 #1244 스위치 켜고 끄기

walbe0528 2024. 7. 7. 11:07
728x90
반응형

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

 

import sys
input = sys.stdin.readline

def on_off(i):
            if switch[i] == 0:
                switch[i] = 1
            else:
                switch[i] = 0

def same_switch(switch, pos):
    on_off(pos-1)
    for i in range(1, N//2):
        left = pos-i-1
        right = pos+i-1
        if left >= 0 and right < N:  # 범위 밖으로 안 벗어나고
            if switch[left] == switch[right]:  # 대칭인 경우
                on_off(left)
                on_off(right)
                # print(*switch)
                continue
            else:
                break
        else:
            break

N = int(input())
switch = list(map(int, input().split()))
num = int(input())
students = [list(map(int, input().split())) for _ in range(num)]

for s, pos in students:
    if s == 1:  # 남자
        for i in range(len(switch)):
            if (i + 1) % pos == 0:
                on_off(i)
    elif s == 2:  # 여자
        same_switch(switch, pos)

for i in range(len(switch)):
    print(switch[i], end=' ')
    if i % 20 == 19:
        print()

 

스위치 입력을 인덱스가 0인 것부터 받아서 마지막에 출력시 나머지가 19인 지점에서 줄바꿈 해줬다.

 

 

좀 더 깔끔한 풀이!

import sys
input = sys.stdin.readline

N = int(input())
switch = [0] + list(map(int, input().split()))
num = int(input())

for _ in range(num):
    student, number = map(int, input().split())
    if student == 1:  # 남자이면
        for i in range(1, N//number+1):
            switch[number * i] = 0 if switch[number*i] == 1 else 1
    else:  # 여자이면
        switch[number] = 0 if switch[number] == 1 else 1
        left, right = number-1, number+1
        while left > 0 and right <= N and switch[left] == switch[right]:
            if switch[left] == 0:
                switch[left], switch[right] = 1, 1
            else:
                switch[left], switch[right] = 0, 0
            left -= 1
            right += 1


for i in range(1, N+1):
    print(switch[i], end=' ')
    if i % 20 == 0:
        print()

 

 

📌 다시 봐야 할 부분

  1. switch를 입력받을 때, 앞에 배열 [0]을 넣어서 시작점이 1이 되도록 맞춰준다
  2. if else를 한줄에 써서 좀 더 가독성 있게 작성하기!
728x90