Hanbit the Developer

[Python] 백준 2138번: 전구와 스위치 본문

Algorithm/백준

[Python] 백준 2138번: 전구와 스위치

hanbikan 2021. 5. 24. 11:49

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

 

2138번: 전구와 스위치

N개의 스위치와 N개의 전구가 있다. 각각의 전구는 켜져 있는(1) 상태와 꺼져 있는 (0) 상태 중 하나의 상태를 가진다. i(1<i<n)번 스위치를="" 누르면="" i-1,="" i,="" i+1의="" 세="" 개의="" 전구의="" 상태가="" 바뀐다.="" 즉,="" 꺼<="" p=""> </i<n)번>

www.acmicpc.net

import sys
import copy
input = sys.stdin.readline


def switch(index, map):
    for i in range(index-1, index+2):
        if 0 <= i <= N-1:
            map[i] = not map[i]

    return map


def getSwitchCount(map, count):
    switchCount = count
    newMap = copy.deepcopy(map)

    for i in range(1, N):
        if newMap[i-1] == True:
            newMap = switch(i, newMap)
            switchCount += 1

    # 모두 False인지 확인
    for i in range(N):
        if newMap[i] == True:
            return -1

    return switchCount


N = int(input())

input1 = input().rstrip()
input2 = input().rstrip()
# True -> False로 바꿔야함
map = [input1[i] != input2[i] for i in range(N)]

switchCountWithoutSwitchingZero = getSwitchCount(map, 0)
if switchCountWithoutSwitchingZero != -1:
    print(switchCountWithoutSwitchingZero)
else:
    print(getSwitchCount(switch(0, map), 1))

 

우선 입력1, 입력2를 비교하여 다른 것들을 True, 같은 것들은 False로 저장하는 리스트를 하나 만든다. 목표는 모든 True를 False로 바꾸는 것이다.

다음은 getSwitchCount() 함수에 대한 설명이다. for문을 i에 대해 1~N-1까지 돌면서 i-1이 True이면 i에 대해 스위치 연산을 수행(switch() 함수)한다. 이후에 그렇게해서 바뀐 맵이 모두 False인지 확인하고 이에 따라 -1 또는 switchCount를 리턴해준다.

다만 특이점은, 1~N-1에 대해 for문을 돌기 때문에 0번째 인덱스에 대한 고려를 하지 못한다는 것이다. 따라서, 0번째 인덱스에 대해 2가지 경우를 나누어서 고려하면 된다.

'Algorithm > 백준' 카테고리의 다른 글

[Python] 백준 12970번: AB  (0) 2021.05.25
[Python] 백준 1080번: 행렬  (0) 2021.05.24
[Python] 백준 2580번: 스도쿠  (0) 2021.05.21
[Python] 백준 1005번: ACM Craft  (0) 2021.05.20
[Python] 백준 1707번: 이분 그래프  (0) 2021.05.19