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

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

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

I solved this question 1461D using a brute force method to find all valid sums in the array but one of my submission which seems correct to me doesnt seem to be working while another submission which is quite similar but just involves splitting and using it in a new vector gives a correct answer. Please help ?

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

»
4 года назад, # |
Rev. 2   Проголосовать: нравится +7 Проголосовать: не нравится

Pass your vector by reference and that's all.

void rec(vt<int> a, int lo, int hi){

Correct one:

void rec(vt<int> &a, int lo, int hi){

I have resubmitted it here: 101179136

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

    Thanks for that can you pls explain why it works that way ?

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

      Every time the function is called, a separate copy of the vector is created. By passing it by reference, you can avoid that. That applies to strings too, or any other "large container"

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

      You should always pass vector by reference to a function.

      If a vector is passed by value, a new temporary vector will be copied. And copying a vector means dynamically allocating new memory for a new vector, copying all elements so it's much more slower.

      If the vector is small, there is no problem, but if it is large, then the parameter-passing itself could consume a lot of resources.

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

        Ok thanks for your help

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

        But if without reference it means that we are copying the vector repeatedly then this submission which creates new vector for every stage also shouldnt work . Can you pls explain why this one works correctly ?

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

          Because he's not passing the whole vector. He's dividing current vector into two halves, So in every recursion call vector size is reduced to half so space would be ONlogN.