Two sequences A and B each of which consist of distinct elements . Find the lcs of two sequences. I have read an explanation on stack overflow but I was not able to understand. Please help with this...
# | User | Rating |
---|---|---|
1 | tourist | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 161 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | awoo | 154 |
8 | Dominater069 | 154 |
10 | luogu_official | 151 |
Two sequences A and B each of which consist of distinct elements . Find the lcs of two sequences. I have read an explanation on stack overflow but I was not able to understand. Please help with this...
Name |
---|
Hint: If $$$A = [1, 2, 3, ..., N]$$$, then it's easy to see that you have to compute the longest increasing subsequence of $$$B$$$.
It can be solved using segment tree. If the numbers are not in the range 1 ~ N then compress the array.
see this problem
Solution -
Precompute the indexes for all A[i] and store in a map.
We maintain a res[] array, where res[i] contains the result when we consider B[i] to be the last element of our LCS.
Iterate the sequence B, for each B[i] :
1) If there is no appearance of B[i] in A, skip that element.
2) Now considering this position to be the last for our LCS, only those B[i]'s can contribute to the LCS, whose value in A have appeared before the index where our current value is present in A(which is map[B[x]]).
Then for our current position(i.e. x), res[x] = max(res[0, 1, ... map[B[x]] — 1]) + 1.
So as to calculate the res[x], we need a BIT/Seg tree (coz we need to update and do max range queries).
Soln