void dfs(int u){ for(int i = head[u];i!=-1;i = edge.next){ int to = dege[i].to; if(to == p[u][0]) continue; d[to] = d[u]+1; dis[to] = dis[u]+edge[i].w; p[to][0] = u; dfs((to)); } } void init(){ for(int j = 1;(1<<j)<=n;j++) for(int i = 1;(1<<i)<=n;i++){ p[i][j] = p[p[i][j-1]][j-1]; } } int lca(int a,int b){ if(d[a]>d[b]) swap(a,b);//b在下面; int f = d[b]-d[a];//f是高度差; for(int i = 0;(1<<i)<=f;i++) if(((1<<i))&f) b = p[b][i]; if(a!=b){ for(int i = (int lomg2(n));i>=0;i--) if(p[a][i]!= p[b][i])//从最大的祖先开始,判断a,b的祖先是否相同 a = p[a][i],b = p[b][i];//如果不相同,a和b同时向上移动2^j a = p[a][0]; } return a; }
时间: 2024-10-16 19:51:03