Sorting by key with duplicate removal
C++
Hard
sorting
Task «Sorting by key with duplicate removal»
Given an array of integers. It is necessary to sort it in ascending order, removing all duplicate values, but with one condition: if a number occurs more than once, then after removing duplicates, its index in the sorted array (zero-based) must be equal to the number of its occurrences in the original array minus one. In other words, for each unique value x that occurs k times in the original array, there must be exactly one occurrence of x in the resulting array, and its index must be equal to k-1. If for some x this is impossible (for example, the index is out of bounds or already occupied by another number), then such x is not included in the result. It is guaranteed that for all numbers that need to be included, the condition is satisfiable. Output the final array, sorted in ascending order.
Input Format
First line: an integer n (1 ≤ n ≤ 10^5) — the number of elements. Second line: n integers, each not exceeding 10^9 in absolute value, separated by spaces.
Output Format
In the first line, output the number m — the number of elements in the resulting array. In the second line, output m integers in ascending order.
Examples
Example 1
INPUT
6
3 1 2 2 3 1
OUTPUT
1
3
Example 2
INPUT
5
5 5 5 5 5
OUTPUT
1
5
Example 3
INPUT
5
Математика Иванов 101 2 3
Физика Петров 202 3 2
Математика Иванов 101 2 3
Химия Сидоров 303 4 1
Физика Петров 202 3 2
OUTPUT
3
Математика Иванов 101 2 3
Физика Петров 202 3 2
Химия Сидоров 303 4 1
Example 4
INPUT
7
4 2 4 2 4 2 4
OUTPUT
2
2 4
Example 5
INPUT
3
Алгебра Смирнов 105 1 1
Алгебра Смирнов 105 1 1
Геометрия Смирнов 105 1 2
OUTPUT
2
Алгебра Смирнов 105 1 1
Геометрия Смирнов 105 1 2
main.cpp