Ishan.nitj's blog

By Ishan.nitj, history, 8 years ago, In English

I am trying to solve this problem http://codeforces.net/contest/652/problem/D. My approach is http://codeforces.net/contest/652/submission/18906153 which is nlogn and should pass the time constraint.However I am getting TLE. I think this might be due std::distance which i have used to calculate distance b/w 2 elements in set.Please HELP.

  • Vote: I like it
  • +4
  • Vote: I do not like it

»
8 years ago, # |
  Vote: I like it +6 Vote: I do not like it

For random access iterators, std::distance is O(1). Unfortunately set iterator does not support random access, so the std::distance algorithm has to iterate over the pointers to compute distance, and worst case is O(n). You can achieve O(1) distance calc in sets if you use order-statistic balanced BST (there is some post in Codeforces teaching how to build this data structure using some hidden C++ libraries)

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

    Can you provide the link to it? Also whats the time complexity with std::vector

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

      For std::vector complexity is O(1) since the iterators support random access. You can also use subtraction operator with the same effect.

      Example : (int) (lower_bound(V.begin(),V.end(),X) — V.begin()) returns distance from begin to first element in array with value >= X, so it's the same as std::distance(V.begin(), lower_bound(V.begin(),V.end(),X))

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