Solve 100 past questions that beginners and intermediates should solve in Python. The goal is to turn light blue by the time you finish solving everything.
This article is "053 --055 Dynamic Programming: Others".
As you can see from "Other", these three questions are a little different from the previous `` `dp``` in terms of orientation (preference?) I felt that.
import bisect
n = int(input())
A = [int(input()) for _ in range(n)]
dp = [A[0]]
for i in range(1, n):
if A[i] > dp[-1]:
dp.append(A[i])
else:
ind = bisect.bisect_left(dp, A[i])
dp[ind] = A[i]
print(len(dp))
It is solved by binary search and DP.
dp
In ascending ordera
We will add the elements of.
In particular,
A
elements ```A [i] `` ``dp``` to
`dp```A [i] `` `in` `` dp
, so replace it with ```A [i] `` ` dp
is.
import bisect
N = int(input())
C = [int(input()) for _ in range(N)]
dp = [C[0]] #initial value
for i in range(1, N):
if C[i] > dp[-1]:
dp.append(C[i])
else:
ind = bisect.bisect_left(dp, C[i])
dp[ind] = C[i]
print(N - len(dp))
import bisect
from collections import deque
N = int(input())
A = [int(input()) for _ in range(N)]
dp = deque()
dp.append(A[0])
for i in range(1, N):
ind = bisect.bisect_left(dp, A[i])
if ind == 0:
dp.appendleft(A[i])
else:
dp[ind-1] = A[i]
print(len(dp))
Let's change the way of thinking from the above two problems.
In the above two problems, the elements above the maximum value of `` `dpwere
append, This time, the elements below the minimum value are
appendleft```.
Recommended Posts