Wrong LIS Algorithm
Time limit1sMemory limit1024 MB
Given N, M, and K, build a permutation of 1 to N whose LIS has length M and whose greedy output B has length K, or print -1 if none exists.
- Level
Medium6 of 10
- Topics
- Greedy, Array, Implementation
- Solved
- No attempts yet
Problem
Jeonghyeon and Seojun learned an algorithm in their computer science class that finds the length of the longest increasing subsequence (LIS) of a sequence. Jeonghyeon found it too tedious to implement, so he wrote his own (incorrect) algorithm and started solving problems with it. Of course, the algorithm could not solve the problems, and he received "wrong answer" on several homework problems from an online judge.
Given a sequence of length where the -th element is , Jeonghyeon's algorithm builds a sequence as follows and returns it:
B = empty sequence
for i = 1 to n:
if B is empty or the last element of B is less than A_i:
append A_i to the end of B
The sequence returned by the algorithm is an increasing subsequence of , but it is not always the longest one, so the algorithm is incorrect. Seojun noticed the mistake and wants to show Jeonghyeon a counterexample. Jeonghyeon refuses to accept the claim without one.
Seojun wants to find a sequence of length that contains each positive integer from to exactly once, where the longest increasing subsequence has length and the subsequence returned by Jeonghyeon's algorithm has length . Help Seojun find such a sequence.
Input
Three integers , , and are given, separated by spaces. ;
Output
If a sequence that satisfies the conditions exists, print one such sequence. Print its elements in order, separated by spaces. If no such sequence exists, print -1.
Hints
The longest increasing subsequence of a sequence is the longest increasing sequence among all subsequences of .
A subsequence is a sequence obtained by choosing one or more elements of the given sequence and listing them in their original order.
An increasing sequence is a sequence in which every element after the first is greater than the element immediately before it. In other words, if is a sequence of length and holds for all , then is increasing. By this definition, every sequence of length 1 is increasing.
Below are implementations of Jeonghyeon's algorithm in C++, Python 3, and Java.
C++
vector<int> b;
for(int x : a){
if(b.empty() || b.back() < x){
b.push_back(x);
}
}
Python 3
b = []
for x in a:
if not b or b[-1] < x:
b.append(x)
Java
ArrayList<Integer> b = new ArrayList<Integer>();
for(int x : a){
if(b.isEmpty() || b.get(b.size() - 1) < x){
b.add(x);
}
}