Skip to content

Commit ecb8b3c

Browse files
committed
[Gold IV] Title: 전구와 스위치, Time: 20 ms, Memory: 69408 KB -BaekjoonHub
1 parent 7b45563 commit ecb8b3c

2 files changed

Lines changed: 68 additions & 0 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# [Gold IV] 전구와 스위치 - 2138
2+
3+
[문제 링크](https://www.acmicpc.net/problem/2138)
4+
5+
### 성능 요약
6+
7+
메모리: 69408 KB, 시간: 20 ms
8+
9+
### 분류
10+
11+
그리디 알고리즘
12+
13+
### 제출 일자
14+
15+
2025년 8월 15일 15:34:14
16+
17+
### 문제 설명
18+
19+
<p>N개의 스위치와 N개의 전구가 있다. 각각의 전구는 켜져 있는 상태와 꺼져 있는 상태 중 하나의 상태를 가진다. i(1 < i < N)번 스위치를 누르면 i-1, i, i+1의 세 개의 전구의 상태가 바뀐다. 즉, 꺼져 있는 전구는 켜지고, 켜져 있는 전구는 꺼지게 된다. 1번 스위치를 눌렀을 경우에는 1, 2번 전구의 상태가 바뀌고, N번 스위치를 눌렀을 경우에는 N-1, N번 전구의 상태가 바뀐다.</p>
20+
21+
<p>N개의 전구들의 현재 상태와 우리가 만들고자 하는 상태가 주어졌을 때, 그 상태를 만들기 위해 스위치를 최소 몇 번 누르면 되는지 알아내는 프로그램을 작성하시오.</p>
22+
23+
### 입력
24+
25+
<p>첫째 줄에 자연수 N(2 ≤ N ≤ 100,000)이 주어진다. 다음 줄에는 전구들의 현재 상태를 나타내는 숫자 N개가 공백 없이 주어진다. 그 다음 줄에는 우리가 만들고자 하는 전구들의 상태를 나타내는 숫자 N개가 공백 없이 주어진다. 0은 켜져 있는 상태, 1은 꺼져 있는 상태를 의미한다.</p>
26+
27+
### 출력
28+
29+
<p>첫째 줄에 답을 출력한다. 불가능한 경우에는 -1을 출력한다.</p>
30+
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
let n = Int(readLine()!)!
2+
let goal = readLine()!.map { $0 == "1" ? true : false }
3+
let initial = readLine()!.map { $0 == "1" ? true : false }
4+
var current = initial
5+
6+
var answer = Int.max
7+
var count = 0
8+
9+
current[0] = !current[0]
10+
current[1] = !current[1]
11+
count += 1
12+
13+
for i in 1..<n {
14+
guard current[i-1] != goal[i-1] else { continue }
15+
for j in i-1...i+1 where j >= 0 && j < n {
16+
current[j] = !current[j]
17+
}
18+
count += 1
19+
}
20+
21+
answer = current == goal ? count : answer
22+
23+
current = initial
24+
count = 0
25+
26+
for i in 1..<n {
27+
guard current[i - 1] != goal[i - 1] else { continue }
28+
for j in i - 1...i + 1 where j >= 0 && j < n {
29+
current[j] = !current[j]
30+
}
31+
count += 1
32+
}
33+
34+
answer = current == goal ? count : answer
35+
36+
answer = answer == Int.max ? -1 : answer
37+
38+
print(answer)

0 commit comments

Comments
 (0)