Пожалуйста, подпишитесь на официальный канал Codeforces в Telegram по ссылке https://t.me/codeforces_official. ×

Блог пользователя SAT2020

Автор SAT2020, история, 2 года назад, По-английски

Hey everyone,

I recently wrote my first segment tree program. While it works properly, the tree itself is extremely slow, especially in the build phase. For instance, with just a sample size of 20,000, the tree takes 3.9 seconds to build on Codeforces! I'm wondering what I can do to speed it up, or if slow build times are the natural result of using object-based trees. Also, any general tips for writing trees and increasing their speed would be greatly appreciated!

Here is my code. It takes two numbers as input: t (the number of queries) and n (the size of the dataset). Both queries and the dataset are generated randomly. Please let me know if you have any questions about how the code works.

Code: https://codeshare.io/8pBOLZ

  • Проголосовать: нравится
  • +5
  • Проголосовать: не нравится

»
2 года назад, # |
  Проголосовать: нравится +32 Проголосовать: не нравится
lChild = new SegTree(arr, lm, mid);
rChild = new SegTree(arr, mid+1, rm);

When vector is passed to a function, a copy of vector is created! These two lines make your program time complexity $$$O(n^{2})$$$. Pass vector by reference instead.

  • »
    »
    2 года назад, # ^ |
      Проголосовать: нравится +22 Проголосовать: не нравится

    Thankyou Thankyou Thankyou, I can't believe I missed this!

    • »
      »
      »
      2 года назад, # ^ |
        Проголосовать: нравится 0 Проголосовать: не нравится

      also, if you do really want to speed up segment tree, you can get rid of pointers and use arrays — it will work faster

»
2 года назад, # |
  Проголосовать: нравится -30 Проголосовать: не нравится

fucking amateurs

»
2 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

In fact, you can simply use arrays to store your segment tree: the left child of index i is i*2, and the right child is i*2+1