## https://yukicoder.me/problems/no/818 class SegmentTree: """ 非再帰版セグメント木。 更新は「加法」、取得は「最大値」のもの限定。 """ def __init__(self, init_array): n = 1 while n < len(init_array): n *= 2 self.size = n self.array = [0] * (2 * self.size) for i, a in enumerate(init_array): self.array[self.size + i] = a end_index = self.size start_index = end_index // 2 while start_index >= 1: for i in range(start_index, end_index): self.array[i] = max(self.array[2 * i], self.array[2 * i + 1]) end_index = start_index start_index = end_index // 2 def add(self, x, a): index = self.size + x self.array[index] += a while index > 1: index //= 2 self.array[index] = max(self.array[2 * index], self.array[2 * index + 1]) def get_max(self, l, r): L = self.size + l; R = self.size + r # 2. 区間[l, r)の最大値を求める s = 0 while L < R: if R & 1: R -= 1 s = max(s, self.array[R]) if L & 1: s = max(s, self.array[L]) L += 1 L >>= 1; R >>= 1 return s def main(): N = int(input()) P = list(map(int, input().split())) # LISを計算・それと同時に辞書順最小のLISの部分列を求められるようにする length_array = [float("inf")] * (N + 1) length_array[0] = 0 prev = [-2] * (N + 1) for p in P: low = 0 high = N while high - low > 1: mid = (high + low) // 2 if length_array[mid] < p: low = mid else: high = mid if length_array[high] < p: v = high + 1 else: v = low + 1 length_array[v] = p prev[p] = length_array[v - 1] lis = 0 for i in range(N + 1): if length_array[i] < float("inf"): lis = i min_path = [] s = length_array[lis] while s != 0: min_path.append(s) s = prev[s] min_path.reverse() # 今度は辞書順最大のLISを求める # LISを計算・それと同時に辞書順最小のLISの部分列を求められるようにする length_array = [-float("inf")] * (N + 1) length_array[0] = 10 * N prev = [-2] * (N + 1) for p in reversed(P): low = 0 high = N while high - low > 1: mid = (high + low) // 2 if length_array[mid] > p: low = mid else: high = mid if length_array[high] > p: v = high + 1 else: v = low + 1 length_array[v] = p prev[p] = length_array[v - 1] lis = 0 for i in range(N + 1): if length_array[i] > -float("inf"): lis = i max_path = [] s = length_array[lis] while s != 10 * N: max_path.append(s) s = prev[s] answer = [] for i in range(len(max_path)): if min_path[i] == max_path[i]: answer.append(min_path[i]) print(len(answer)) print(" ".join(map(str, answer))) if __name__ == "__main__": main()