Algorithm (PS)
[백준] 7570번: 줄세우기 Python - Greedy/DP
minjiwoo
2023. 1. 3. 15:48
728x90
https://www.acmicpc.net/problem/7570
7570번: 줄 세우기
입력은 2 개의 줄로 이루어져 있다. 첫 줄에는 어린이 수를 나타내는 정수가 주어진다. 둘째 줄에는 처음에 줄서있는 어린이들의 번호가 차례대로 주어진다. 주어진 번호들 사이에는 공백이 하
www.acmicpc.net
가장 긴 증가하는 수열의 길이를 찾은 후 전체 길이 n에서 빼준다.
n = int(input())
data = list(map(int, input().split()))
count = 1 # 길이가 1 인 수열로 취급
max_len = 0
position = [0] * (n+1)
for i in range(1, len(data)):
position[data[i]] = i # index를 저장한다. I#NDEX를 1 ~ 로 시작하는걸로 맞춰준다.
for i in range(1, len(data)-1):
if position[i] < position[i+1]: # 올바른 순서 , 즉 크기가 증가하는 수열인 경우
count += 1
max_len = max(count, max_len)
else:
count = 1
print(n - max_len)
DP 풀이
import sys
input = sys.stdin.readline
n = int(input())
data = list(map(int, input().split()))
dp = [0]*(n+1)
max_length = 0
for i in range(n):
index = data[i] # position 에 해당 지금 숫자가 dp에 저장될 위치임
dp[index] = dp[index-1] +1
max_length = max(dp)
print(n - max_length)
728x90