아이공의 AI 공부 도전기

[Baekjoon] 1244번 : 스위치 켜고 끄기 (Python, 구현, 시뮬레이션)

 

     

 

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

 

1244번: 스위치 켜고 끄기

첫째 줄에는 스위치 개수가 주어진다. 스위치 개수는 100 이하인 양의 정수이다. 둘째 줄에는 각 스위치의 상태가 주어진다. 켜져 있으면 1, 꺼져있으면 0이라고 표시하고 사이에 빈칸이 하나씩

www.acmicpc.net

 

코드 링크

https://github.com/stellaluminary/Baekjoon

 

GitHub - stellaluminary/Baekjoon

Contribute to stellaluminary/Baekjoon development by creating an account on GitHub.

github.com

 

Python

 

방법 1 - 메모리 30840KB / 시간 76ms / 코드 길이 812B

 

조건에 맞는 구현

출력 유의

 

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

for i in range(int(input())):
    s, g = map(int, input().split())

    if s == 1:
        for j in range(1, len(switch)):
            if j % g == 0:
                switch[j] = 1 if switch[j] == 0 else 0
    else:
        switch[g] = 1 if switch[g] == 0 else 0
        for j in range(1, len(switch)-g):
            if g-j < 1:
                break
            if switch[g-j] == switch[g+j]:
                switch[g-j] = 1 if switch[g-j] == 0 else 0
                switch[g+j] = 1 if switch[g+j] == 0 else 0
            else:
                break

twenty = (len(switch)-1) // 20
for i in range(twenty+1):
    if i == twenty:
        val = switch[20*i + 1:]
    else:
        val = switch[20*i + 1:20*(i+1)+1]
    print(' '.join(map(str, val)))

 

방법 2 - 메모리 30840KB / 시간 76ms / 코드 길이 568B

 

0을 1로 1을 0으로 바꿀 때 dict를 사용하면 유용

출력을 20번째 index마다 내림으로 변환하는 방법 또한 존재

 

 

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

rev = {0:1, 1:0}

for _ in range(int(input())):
    s, g = map(int, input().split())

    if s == 1:
        for j in range(g, n+1, g):
            switch[j] = rev[switch[j]]
    else:
        switch[g] = rev[switch[g]]
        i = 1
        while (g-i >= 1) and (g+i <= n) and (switch[g-i] == switch[g+i]):
            switch[g-i], switch[g+i] = rev[switch[g-i]], rev[switch[g+i]]
            i += 1

for e, v in enumerate(switch[1:], start=1):
    print(v, end=' ')
    if e % 20 == 0:
        print()

 

공유하기

facebook twitter kakaoTalk kakaostory naver band
loading