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

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

Problem statement is here and i am getting TLE for this solution. Looks O(31*N) to me, any idea(s) how to improve??

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

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

The algorithm basically reduces to this: the result for a position i = v[i-k] & v[i-k+1] & ... &v[i] & ... & v[i+k-1] & v[i+k], not taking into account the fact that the array is cyclical. The algorithm that you propose is O(log(maximum value) * N), as you do a pass for each bit in the values of the array. However, we can achieve O(N * log(N)) by using a interval tree which calculates the & value for arbitrary subsegments for the array. By using this, we can do a single pass through the results, and, for each result, calculate the value of v[i-k] & ... & v[i+k] (we have a special case in which either i-k or i+k reaches past the end of the array. Then we have v[0] & ... & v[(i+k)%n] & v[(i-k)&n] & ... & v[n-1], if we index the array v from 0). Since log(N) ~= 15, whereas log(maximum value) ~= 31, with this technique we can halve the execution time.