51 lines
1.6 KiB
Python
51 lines
1.6 KiB
Python
# 가장 긴 증가하는 부분 수열 5
|
|
|
|
import sys
|
|
from bisect import bisect_left
|
|
|
|
input = sys.stdin.readline
|
|
|
|
def solution():
|
|
n = int(input().rstrip())
|
|
|
|
lst = list(map(int, input().rstrip().split()))
|
|
parent = [-1] * (n)
|
|
|
|
result = [lst[0]]
|
|
result_idx = [0]
|
|
for i in range(1, n):
|
|
if lst[i] > result[-1]:
|
|
parent[i] = result_idx[-1]
|
|
result.append(lst[i])
|
|
result_idx.append(i)
|
|
continue
|
|
idx = bisect_left(result, lst[i])
|
|
if result[idx] != lst[i]:
|
|
result[idx] = lst[i]
|
|
result_idx[idx] = i
|
|
if idx != 0:
|
|
parent[i] = result_idx[idx-1]
|
|
|
|
answer = [result[-1]]
|
|
parent_idx = parent[result_idx[-1]]
|
|
while parent_idx != -1:
|
|
answer.append(lst[parent_idx])
|
|
parent_idx = parent[parent_idx]
|
|
|
|
print(len(answer))
|
|
print(*answer[::-1])
|
|
return
|
|
|
|
|
|
solution()
|
|
|
|
"""
|
|
걸린 시간: 2분 ㅋㅋ
|
|
|
|
시간 복잡도: 14002와 같게 모든 수에 대해. 이분 탐색을 진행하기 때문에 O(nlogn)이다.
|
|
|
|
해설: 14002번(가장 긴 증가하는 부분 수열 4) 답을 그대로 가져와서 binary_search를 직접 구현하지 않고, bisect를 활용해서 구현하였다.
|
|
내가 들어갈 자리는 나보다 처음으로 큰 녀석의 자리이기 때문에 사실상 왼쪽으로 들어간다고 생가하면 된다.(오른쪽은 제거하지만..)
|
|
따라서 bisect_left를 활용하였다.
|
|
또한 bisect_left에는 리스트 원소들이 tuple이면 안되기 때문에, result_idx라는 리스트를 따로 만들어서 진행하였다.
|
|
""" |