如题,我用的是倍增LCA,卡常卡疯了也没能卡过去#8和#9,求大佬们帮忙卡常,感激不尽!
%:pragma GCC optimize("Ofast")
%:pragma GCC optimize("unroll-loops")
%:pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cctype>
#define rint register int
inline void read(int &x){x=0;
char ch=getchar();
while(!isdigit(ch)) ch=getchar();
while(isdigit(ch)){
x=x*10+ch-'0';
ch=getchar();
}
}
const int N=5e5;
const int LOG=std::log(N+0.0)/std::log(2.0);
int n,m;
namespace edge
{
int head[N],cnt=0;
struct Edge{
int to,nxt;
}e[N<<1];
inline void add_edge(int u,int v){
e[++cnt]=Edge{v,head[u]};
head[u]=cnt;
}
}
using namespace edge;
namespace LCA
{
int anc[N][LOG+5],depth[N];
int Log;
void dfs(int u,int father){
depth[u]=depth[father]+1;
anc[u][0]=father;
for(int i=head[u];i;i=e[i].nxt){
if(e[i].to!=father)
dfs(e[i].to,u);
}
}
inline void pre(){
Log=std::log(n+0.0)/std::log(2.0);
dfs(1,0);
for(int j=1;j<=Log;++j){
for(int i=1;i<=n;++i){
anc[i][j]=anc[anc[i][j-1]][j-1];
}
}
}
inline int LCA(int x,int y){
if(depth[x]<depth[y]) std::swap(x,y);
int k=depth[x]-depth[y];
for(int i=0;k;++i,k>>=1){
if(k&1) x=anc[x][i];
}
if(y==x) return y;
for(int i=Log;i>=0;--i){
if(anc[x][i]!=anc[y][i]){
x=anc[x][i],y=anc[y][i];
}
}
return anc[x][0];
}
}
int main()
{
read(n);read(m);
int x,y;
for(rint i=1;i<n;++i){
read(x);read(y);
add_edge(x,y);
add_edge(y,x);
}
rint z,ans,ansl,l1,l2,l3;
LCA::pre();
using LCA::depth;
while(m--){
read(x);read(y);read(z);
l1=LCA::LCA(x,y),l2=LCA::LCA(y,z),l3=LCA::LCA(x,z);
if(l1==l2) ansl=l3;
else if(l2==l3) ansl=l1;
else if(l1==l3) ansl=l2;
std::printf("%d %d\n",ansl,depth[x]+depth[y]+depth[z]-depth[l1]-depth[l2]-depth[l3]);
}
return 0;
}