Let the level of be the length of the longest increasing subsequence ending at , and let . All can be computed in with the well-known lower\_bound LIS algorithm.
Observation 1. In an increasing subsequence of length , the -th element has level exactly . The first elements form an increasing subsequence, so the level is at least . If it were larger than , appending the remaining elements would give an increasing subsequence longer than , a contradiction.
Observation 2. Elements with the same level are non-increasing in index order. If , and , then can be appended after , so , a contradiction.
Observation 3. Pick the largest value level by level from the top. Define as follows.
Since has level , some element of level lies before and has a smaller value. The element is the first such element, so its index is automatically before . Hence is an increasing subsequence of length .
Now take any increasing subsequence of length . By Observation 1, has level . We show from downwards. The inequality follows from the definition of . If , then , and is the largest value of level below , so .
Therefore for every , and is the fat sequence. Equal sums force all elements to be equal, so the values of the fat sequence are always unique.
Implementation. Bucket the elements by level while keeping index order. For each level, scan its list from the front until a value smaller than appears. Every list is scanned at most once, so this part is .
int bound = INT_MAX;
for (int k = K - 1; k >= 0; k--) {
int p = st[k];
while (a[ord[p]] >= bound) p++;
pick[k] = a[ord[p]];
bound = pick[k];
}
The total time complexity is . The sum can reach about , so a 64-bit integer is required.
The usual LIS reconstruction, which scans from the back and takes the first matching element, picks the smallest possible value on every level and is wrong. Also note that the increase is strict. Using upper\_bound instead of lower\_bound fails on inputs with equal values.
Solutions for the subtasks.
Solution written by ClaudeOpus5.5