HitmanBBa's blog

By HitmanBBa, history, 9 years ago, In English

Greetings.

There is any O(N LOG K) algorithm for longest not strictly increasing subsequence?

Example for longest not strictly increasing subsequence:

n = 3
a[] = {1, 1, 1}

Normal O(N LOG K) algorithm will give answer = 1. (Because it's work strictly increasing)

I need modified algorithm to give answer = 3.

Thanks in advance.

Tags lis, dp
  • Vote: I like it
  • +8
  • Vote: I do not like it

»
9 years ago, # |
Rev. 3   Vote: I like it +18 Vote: I do not like it
vector<int> input, lis;
int n;//sizeof input
for (int i = 0; i < n; i++){
    int pos = upper_bound(lis.begin(), lis.end(), input[i]) - lis.begin();
    if (pos == lis.size())
         lis.push_back(input[i]);
    else
         lis[pos] = input[i];
}
//lis.size() is the answer
  • »
    »
    9 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Oh man, you saved my life.

    Thank you very much, you are my hero :D.

    • »
      »
      »
      9 years ago, # ^ |
        Vote: I like it +18 Vote: I do not like it

      you're welcome :) if you replace upper_bound with lower_bound, it gives you the normal lis.

      • »
        »
        »
        »
        9 years ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        One last question.

        How to build the solution?

        • »
          »
          »
          »
          »
          9 years ago, # ^ |
            Vote: I like it +12 Vote: I do not like it

          for each i, I define l[i] = longest nondecreasing subsequence which ends on the ith position of input prv[i] = the index which we update l[i] from.

          I modify vector<a[j]> lis to vector<pair<a[j], j>> lis. now you can see that on the ith iteration of the algorithm, we get l[i] = pos, prv[i] = lis[pos — 1].second.

          now run a recursive algorithm starting from such index z that l[z] = lis.size() and use prv to build the solution.