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 | 3993 |
2 | jiangly | 3743 |
3 | orzdevinwang | 3707 |
4 | Radewoosh | 3627 |
5 | jqdai0815 | 3620 |
6 | Benq | 3564 |
7 | Kevin114514 | 3443 |
8 | ksun48 | 3434 |
9 | Rewinding | 3397 |
10 | Um_nik | 3396 |
# | User | Contrib. |
---|---|---|
1 | cry | 167 |
2 | Um_nik | 163 |
3 | maomao90 | 162 |
3 | atcoder_official | 162 |
5 | adamant | 159 |
6 | -is-this-fft- | 158 |
7 | awoo | 155 |
8 | TheScrasse | 154 |
9 | Dominater069 | 153 |
10 | djm03178 | 152 |
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