백준 온라인 저지, 그리디 / 3088번: 화분부수기 (파이썬 / 백준 골드문제)

2021. 11. 20. 00:17알고리즘/그리디

728x90
반응형

문제

상근이는 K512 뒤쪽에 화분 N개를 놓았다. 태완이는 이 화분을 모두 부수어 버리려고 한다. 화분은 한 줄로 놓여져 있으며, 세 정수가 쓰여져 있다.

태완이가 화분 하나를 깼을 때, 그 화분에 쓰여있는 숫자와 오른쪽에 있는 임의의 화분에 쓰여있는 숫자가 하나라도 겹친다면 해당하는 화분은 깨진다. 이것은 연쇄적으로 일어난다. 따라서, 태완이는 화분 하나만 깨서 모든 화분을 깰 수 있다.

의외로 게으른 아이인 태완이는 되도록 적은 수의 화분을 직접 깨서 모든 화분을 깨지게 만들려고 한다. 이때, 태완이가 직접 깨야하는 화분의 최소 개수를 구하는 프로그램을 작성하시오.

위의 그림에서 2번 화분을 깬다면, 3번과 4번 화분은 숫자 2가 겹치기 때문에 화분이 깨지며, 숫자 9가 겹치기 때문에 화분 5가 깨지게 된다. 이제 남은 화분은 1번이기 때문에, 1번만 깨면 모든 화분을 깰 수 있다. 태완이는 화분 두 개를 직접 깨서 모든 화분을 깰 수 있다.

입력

첫째 줄에 화분의 개수 N이 주어진다. (1 ≤ N ≤ 300,000)

다음 N개 줄에는 각 화분에 쓰여 있는 숫자 세 개 Ai, Bi, Ci가 놓여져 있는 순서대로 주어진다. (1 ≤ Ai, Bi, Ci ≤ 1,000,000)

출력

첫째 줄에 태완이가 직접 깨야하는 화분 개수의 최솟값을 출력한다.

예제 입력 1

3
1 2 3
2 3 4
4 5 6

예제 출력 1

1

예제 입력 2

5
3 4 1
2 5 6
7 2 8
2 1 9
11 10 9

예제 출력 2

2
W3sicHJvYmxlbV9pZCI6IjMwODgiLCJwcm9ibGVtX2xhbmciOiIwIiwidGl0bGUiOiJcdWQ2NTRcdWJkODQgXHViZDgwXHVjMjE4XHVhZTMwIiwiZGVzY3JpcHRpb24iOiI8cD5cdWMwYzFcdWFkZmNcdWM3NzRcdWIyOTQ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yaXRlIHRoZSBtaW5pbWFsIG51bWJlciBvZiBwb3RzIE1hcnRpbiBoYXMgdG8gY3Jhc2ggaGltc2VsZiB0byBjcmFzaCBhbGwgdGhlIHBvdHMuJm5ic3A7PFwvcD5cclxuIiwiaGludCI6IiIsIm9yaWdpbmFsIjoiMSIsImh0bWxfdGl0bGUiOiIwIiwicHJvYmxlbV9sYW5nX3Rjb2RlIjoiRW5nbGlzaCJ9XQ==

접근 방법

- 가장 왼쪽부터 순서대로 화분을 깨며 해당하는 숫자를 인덱스를 통해 dp에 1을 저장한다.
- 만약 화분을 깼을 때 이미 깬 화분의 숫자를 포함하고 있다면 그 화분은 숫자를 더하지 않는다.
- 만약 화분을 깼을 때 숫자가 없다면 dp에 해당 값들을 모두 저장하고 카운트를 추가한다.
- 모든 화분을 탐색한 뒤, 카운트를 출력한다.

코드

# https://www.acmicpc.net/problem/3088
# 접근방법
# 가장 왼쪽부터 순서대로 화분을 깨며 해당하는 숫자를 인덱스를 통해 dp에 1을 저장한다.
# 만약 화분을 깼을 때 이미 깬 화분의 숫자를 포함하고 있다면 그 화분은 숫자를 더하지 않는다.
# 만약 화분을 깼을 때 숫자가 없다면 dp에 해당 값들을 모두 저장하고 카운트를 추가한다.
# 모든 화분을 탐색한 뒤, 카운트를 출력한다.
import sys
input = sys.stdin.readline
n = int(input())
pot = [list(map(int, input().split())) for _ in range(n)]
count = 0
dp = [0 for _ in range(10**6 + 1)]
for a, b, c in pot:
    if not dp[a] and not dp[b] and not dp[c]:
        count += 1
    dp[a], dp[b], dp[c] = 1, 1, 1
print(count)
728x90
반응형