__yql0991888__'s blog

By __yql0991888__, history, 2 weeks ago, In English

If you have a brute force solution runs 10 seconds, but time limit is 2 seconds, stop thinking the correct solution, go to optimize your brute force solution.

Problem: https://qoj.ac/problem/8616

This problem is weird: it requires tree path addition and tree path XOR sum queries.

If the queries were on a sequence rather than a tree, use this approach and you will get an $$$O(q\sqrt{n}\log n\log V)$$$ solution. By combining this with heavy-light decomposition, we can solve the tree version in $$$O(q\sqrt{n} \log^2 n\log V)$$$ time with a high constant factor, cannot pass the time limit. It's even slower than brute force under these constraints!

Now we think of brute force.

The basic brute force approach is, for two nodes $$$u$$$ and $$$v$$$, find their LCA, and move both $$$u,v$$$ upward toward their LCA, update all the elements on the path. This is slow, isn't it? On modern computers, contiguous memory access is faster than random memory access. So we can use heavy-light decomposition to turn the random accesses into $$$O(\log n)$$$ contiguous segments. Then, with #pragma GCC optimize("O3,unroll-loops") and #pragma GCC target("avx2,sse4.2,avx512f"), so you can get accepted on this problem.

Try it! https://qoj.ac/problem/8616

  • Vote: I like it
  • -19
  • Vote: I do not like it

»
2 weeks ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by __yql0991888__ (previous revision, new revision, compare).

»
2 weeks ago, hide # |
 
Vote: I like it +13 Vote: I do not like it

Computers are fast nowadays, so we can solve this problem in O(nq).

»
2 weeks ago, hide # |
Rev. 2  
Vote: I like it +8 Vote: I do not like it

I believe you have learned this trick. So lets do a little exercise now!

Spoiler