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

Автор bablu_45, история, 5 лет назад, По-английски

We are given an array of size 'N' with 'Q' queries. Each query contains 3 integers (A,B and C) which divides the entire array into 4 parts or subarrays, [0,A-1],[A,B],[B+1,C] and [C+1,N-1]. We need to swap first and second subarray and third and fourth subarray.

You need to output the final array after Q queries.

Constraints:

1<=N<=10^5

1<=Q<=10^5

1<=A[i]<=10^9.

Eg:- N=9 with 2 queries

9 2

1 2 3 4 5 6 7 8 9

2 4 6

1 3 5

In first query we are supposed to swap [0,1] and [2,4], [5,6] and [7,8]. So after first query array becomes [3,4,5,1,2,8,9,6,7]

In second query we are supposed to swap [0,0] and [1,3], [4,5] and [6,8] of modified array. So final array is [4,5,1,3,9,6,7,2,8]

How to solve this question?

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

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

You should read about treap, it can be used to solve this.

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

    treap-is-like-this-knife
    After seeing so many similar comments about treap, now I start imagining treap as a weapon like this. :D

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

      Treap is just easy to implement. You need to implement split, merge and a function to update nodes, all of them are at most 10-15 lines of code. With it you can make an array where you can access element, split it into parts and merge them in $$$O(\log n)$$$

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

Make a temporary array that will tell you final index of all the elements. For every query shift the elements from 0 to A-1 by A units(simply by adding +A at index -1 and -A at index A) and elements from A to B by -A units by a similar strategy. Do the same for B to N. When all the queries are over simply do a prefix sum calculation over this array. The final value will tell you the modified index.

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

    I don't think it will work as the positions of every element changes after each query and for the next query we need to modify the elements/sub-arrays according to the new positions.