## 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を計算 length_array = [float("inf")] * (N + 1) length_array[0] = 0 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 lis = 0 for i in range(N + 1): if length_array[i] < float("inf"): lis = i # あるiについて抜いたらLIS = lisが実現できないか?みたいものを計算する # Backward計算 backward_segtree = SegmentTree([0] * (N + 1)) backward_value = [-1] * N for i in reversed(range(1, N)): p = P[i] l = backward_segtree.get_max(p + 1, N + 1) backward_segtree.add(p, l + 1) backward_value[i] = l + 1 def get_length(low, high, length_array): while high - low > 1: mid = (high + low) // 2 if length_array[mid] < float("inf"): low = mid else: high = mid if length_array[high] < float("inf"): return high else: return low length_array = [float("inf")] * (N + 1) length_array[0] = 0 answer = [] prev_len = -1 for i in range(N): length = backward_segtree.get_max(0, N + 1) length2 = get_length(0, N, length_array) if length < lis and length2 < lis: length = backward_segtree.get_max(P[i - 1] + 1, N + 1) if length + prev_len < lis: answer.append(i) if i < N - 1: low = 0 high = N p = P[i] 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_len = v backward_segtree.add(P[i + 1], -backward_value[i + 1]) backward_value[i + 1] = 0 print(len(answer)) print(" ".join(map(lambda x : str(P[x]), answer))) if __name__ == "__main__": main()