大佬求助! 3个TLE,2个MLE (QAQ)
#include<bits/stdc++.h>
using namespace std;
const int SIZE=500005,LOG=18;
int n,m,s,head[SIZE],cnt=1,depth[SIZE],hop[SIZE][LOG];
struct node{
int to,next;
}edge[SIZE];
void add(int u,int v)
{
edge[cnt].to=v;
edge[cnt].next=head[u];
head[u]=cnt++;
}
void dfs(int u,int fa,int d)
{
depth[u]=d;
hop[u][0]=fa;
int son;
for(int i=head[u];i;i=edge[i].next)
{
son=edge[i].to;
if(son==fa)
{
continue;
}
dfs(son,u,d+1);
}
}
void init()
{
dfs(s,0,1);
for(int i=1;i<LOG;i++)
{
for(int j=1;j<=n;j++)
{
hop[j][i]=hop[hop[j][i-1]][i-1];
}
}
}
void deepunf(int &u,int h)
{
for(int i=0;h;i++)
{
if(h&1)
{
u=hop[u][i];
}
h>>=1;
}
}
int lca(int u,int v)
{
if(depth[u]!=depth[v])
{
if(depth[u]<depth[v])
{
swap(u,v);
}
deepunf(u,depth[u]-depth[v]);
}
if(u==v)
{
return u;
}
for(int i=LOG-1;i>=0;i--)
{
if(hop[u][i]!=hop[v][i])
{
u=hop[u][i];
v=hop[v][i];
}
}
return hop[u][0];
}
int main()
{
scanf("%d%d%d",&n,&m,&s);
int u,v;
for(int i=1;i<n;i++)
{
scanf("%d%d",&u,&v);
add(u,v);
add(v,u);
}
init();
for(int i=1;i<=m;i++)
{
scanf("%d%d",&u,&v);
printf("%d\n",lca(u,v));
}
return 0;
}
望大佬帮帮忙!