求树上的两个点的最小公共祖先的算法。
void fill()
{
for(int i
=1;i
<=29;i
++)
for(int j
=1;j
<=n
;j
++)
f
[j
][i
]=f
[f
[j
][i
-1]][i
-1];
}
int lca(int x
,int y
)
{
if(depth
[x
]<depth
[y
]) swap(x
,y
);
for(int i
=29;i
>=0;i
--)
if(depth
[f
[x
][i
]]>=depth
[y
])
x
=f
[x
][i
];
if(x
==y
)return x
;
for(int i
=29;i
>=0;i
--)
if(f
[x
][i
]!=f
[y
][i
])
{
x
=f
[x
][i
],y
=f
[y
][i
];
}
return f
[x
][0];
}
谢谢阅读
转载请注明原文地址: https://lol.8miu.com/read-38615.html