Блог пользователя nkb-xyz

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

How to efficiently count the number of pairs having a xor b equal to m where 1<=a<=n , 1<=b<=n and n varies 2 to 2e5 and m also varies 1 to n

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

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

Hint: If a and m are fixed, can you find a value of b, such that a ^ b = m?

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

digit dp helps solve this problem with ease with larger N I guess

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

If you look at all bits in m, then if bit is 0, than this bit is same in a and b and if 1 than different. This already gives a linear time algorithm (you can take first bit, and go in two same recursion but memorizing how you change bit in a and b. It hase exponential branche factor but logariphmic number of levels, so it is linear. In other words, it works in O(2^{log(n)})=O(n)).

Let f(x,y,m,i) be function that return number of pairs a and b such that 1<=a<=x and 1<=b<=y and a^b=m and proccess only bits from 1 to i. Looking at the biggest bit of m, we can go in recursion same as in the solution above (if there should be i-th bit 1 in a and 0 in b, then return f(x-(1<<i),y,m-(1<<i),i-1)+f(x,y-(1<<i),m-(1<<i),i-1) for example). If x or y is 1, we can easily get answer (1^x would be x+1 or x-1, so it is just some ifs). Let's check some edge cases. If x>(1<<(i+1))-1 then we can make any number from bits from 1 to i, so we can assign x=(1<<(i+1))-1. Same for y. If x and y are powers of 2 minus 1, we can solve it easily. Firstly, if x=y and x=(1<<n)-1, then answer is x, because for any x, m^x is at most y (we assume that m has only i bits, because otherwise there are 0 pairs). Assume that y>x and y and x are power of 2 minus 1. Then we can assign any a and b will be m^a and there will also be such solution. So number of solutions are also x. If x<(1<<i), then we cannot decrease it in the recursion. Same for y.

Having all this we can come up with some solution. I believe it should work in O(log(n)), but it is clearly less then O(n). Here is code what I mean

Code

This code doesn't work now, but it should show the idea that I mean. Also, with this if's it should also go in two recursions, but one of them will get into some of first if's, so should proccess in constant time.