Last active
July 19, 2020 03:54
-
-
Save cgiosy/df7443d1dd80fa27f3f62ac8ccb0a2ea to your computer and use it in GitHub Desktop.
Optimal node ranking of a tree.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// int rank[N]; vector<int> G[N]; | |
auto rank_tree(int i, int p=-1) { | |
int x=0, y=0; | |
for(int j:G[i]) if(j!=p) { | |
auto z=rank_tree(j, i); | |
y|=x&z, x|=z; | |
} | |
x=(x|(1<<31-__builtin_clz(y<<1|1))-1)+1; | |
rank[i]=__builtin_ctz(x); | |
return x; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
용어:
알고리즘:
구현:
01001011
→01001100
(1<<31-__builtin_clz(y<<1|1))-1
으로 구할 수 있고, 이를 x와 OR 연산한 뒤 +1을 해주면 i에 rank를 부여한 뒤의 x를 구할 수 있다.__builtin_clz
는 입력으로 들어온 수가 0이면 UB이기 때문에, 위 코드를(1<<32-__builtin_clz(y))-1
로 대체할 수는 없다.__builtin_ctz(x)
이고, 최대 rank(혹은 깊이)는31-__builtin_clz(x)
이다.