이번 포스팅에서는 백준 골드5 2138번 전구와 스위치를 파이썬으로 푼 것에 대해 설명하겠습니다.
https://www.acmicpc.net/problem/2138
2138번: 전구와 스위치
N개의 스위치와 N개의 전구가 있다. 각각의 전구는 켜져 있는 상태와 꺼져 있는 상태 중 하나의 상태를 가진다. i(1 < i < N)번 스위치를 누르면 i-1, i, i+1의 세 개의 전구의 상태가 바뀐다. 즉, 꺼져
www.acmicpc.net
전구와 스위치 정답 코드
# 전구와 스위치
# 복습 횟수:1, 00:45:00, 복습필요X
import sys
si = sys.stdin.readline
N = int(si())
current_state = list(map(int, si().rstrip()))
hope_state = list(map(int, si().rstrip()))
def converter(index, coped_state):
if coped_state[index] == 1:
coped_state[index] = 0
else:
coped_state[index] = 1
# 맨 앞과 맨 끝만 차이가 있다.
# 맨 처음을 누른 경우
answer = []
def on_off(candidate):
for i in range(1, len(coped_state)):
if i == len(coped_state) -1: # 마지막 인덱스인 경우
if coped_state[i-1] != hope_state[i-1]:
candidate += 1
converter(i-1, coped_state)
converter(i, coped_state)
else:
if coped_state[i-1] != hope_state[i-1]:
candidate += 1
converter(i-1, coped_state)
converter(i, coped_state)
converter(i+1, coped_state)
return candidate
coped_state = current_state[:]
candidate1 = 1
converter(0, coped_state)
converter(1, coped_state)
candidate1 = on_off(candidate1)
if coped_state == hope_state:
answer.append(candidate1)
# 맨 처음을 누르지 않은 경우
candidate2 = 0
coped_state = current_state[:]
candidate2 = on_off(candidate2)
if coped_state == hope_state:
answer.append(candidate2)
if len(answer) == 0:
print(-1)
else:
print(min(answer))
전구와 스위치 풀이 아이디어
1. 전구를 앞에서부터 세팅한다고 생각합니다. 앞의 것이 세팅되면 그것을 기준으로 그 다음 것을 킬지 말지가 결정되기 때문입니다. ( 바로 앞전구에 영향을 줄 수 있는 것은 자기 자신이 아니면 그 다음 전구밖에 없습니다.)
2. 첫번째와 두번째 전구를 켠 경우와 키지 않은 경우의 두 가지 케이스가 있습니다. (직접 해보시면 다른 케이스가 됨을 알
수 있습니다.)
전구와 스위치 코드 해설
1. 맨 처음을 누른경우와 누르지 않은 경우로 나누었습니다.
2. converter 함수를 만들어 0인 경우 1로 1인 경우 0으로 스위치를 조절하였습니다.
3. on_off 함수를 만들어 index 1부터 끝까지 앞의 전구를 기준으로 스위치를 켜고 껐습니다. 마지막 인덱스인 경우는 그 다음 전구가 없으므로 if 문으로 구분해주었습니다.
4. on_off 함수를 다 돌고나서 만약 같은 경우엔 가능한 케이스이므로 answer 에 후보로 담아주었습니다.
5. 만약 두 케이스 모두 담기지 않은 경우는 answer에 아무것도 없으므로 len(answer) == 0: 일때로 모두 안되는 경우를 구분해주었습니다.