Skip to content

Instantly share code, notes, and snippets.

@BreadFish64
Created September 28, 2019 22:54
Show Gist options
  • Save BreadFish64/77a6e00f8440b33bc365c1d6813d0625 to your computer and use it in GitHub Desktop.
Save BreadFish64/77a6e00f8440b33bc365c1d6813d0625 to your computer and use it in GitHub Desktop.
#include <cstdint>
#include <iostream>
#ifdef _MSC_VER
#include <intrin.h>
#define clz(x) __lzcnt64(x)
#else
#define clz(x) __builtin_clzll(x)
#endif
using u64 = std::uint64_t;
u64 TreeDist(u64 a, u64 b) {
if (a < b)
std::swap(a, b);
u64 ms_one = clz(b) - clz(a);
u64 x = (a >> ms_one) ^ b;
// clz on 0 is undefined, gcc returns 63
if (x)
x = 2 * (64 - clz(x));
return x + ms_one;
}
int main() {
unsigned q = 0;
std::cin >> q;
for (unsigned i = 0; i < q; ++i) {
std::uint64_t a, b;
std::cin >> a >> b;
std::cout << TreeDist(a, b) << '\n';
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment