Codechef TALCA 最近公共祖先技巧

文章目录

题意

, q , r , u , v . 给出一棵树,回答q个询问,每次求以r为根,u,v的最近公共祖先.

题解

本来指望一波分讨的,很烦,一点都不想写.
有没有简单一点的办法呢?
假设 p 1 p1 u , v u,v 的最近公共祖先, p 2 p2 u , r u,r 的最近公共祖先, p 3 p3 v , r v,r 的最近公共祖先.
在脑子里稍微模拟一下,找棵点数比较多的树手玩一下,大胆猜一波结论,答案就是 p 1 , p 2 , p 3 p1,p2,p3 中深度最大的点.
看来我猜对了.但是我还不会证,求教大佬.
l c a lca 用的是树剖,常数小得惊人,轻松碾压获得时间 r a n k 1 rank1 .

#include<bits/stdc++.h> //Ithea Myse Valgulious
namespace chtholly{
typedef long long ll;
#define re0 register int
#define rel register ll
#define rec register char
//#define gc getchar
#define gc() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<23,stdin),p1==p2)?-1:*p1++)
#define pc putchar
#define p32 pc(' ')
#define pl puts("")
/*By Citrus*/
char buf[1<<23],*p1=buf,*p2=buf;
inline int read(){
  int x=0,f=1;char c=gc();
  for (;!isdigit(c);c=gc()) f^=c=='-';
  for (;isdigit(c);c=gc()) x=(x<<3)+(x<<1)+(c^'0');
  return f?x:-x;
  }
template <typename mitsuha>
inline bool read(mitsuha &x){
  x=0;int f=1;char c=gc();
  for (;!isdigit(c)&&~c;c=gc()) f^=c=='-';
  if (!~c) return 0;
  for (;isdigit(c);c=gc()) x=(x<<3)+(x<<1)+(c^'0');
  return x=f?x:-x,1;
  }
template <typename mitsuha>
inline int write(mitsuha x){
  if (!x) return 0&pc(48);
  if (x<0) pc('-'),x=-x;
  int bit[20],i,p=0;
  for (;x;x/=10) bit[++p]=x%10;
  for (i=p;i;--i) pc(bit[i]+48);
  return 0;
  }
inline char fuhao(){
  char c=gc();
  for (;isspace(c);c=gc());
  return c;
  }
}using namespace chtholly;
using namespace std;
const int yuzu=2e5;
vector<int> lj[yuzu|10];
typedef int fuko[yuzu|10];
namespace {
fuko dep,fa,son,sz,ord,dfn,top;
void dfs(int u,int f){
  sz[u]=1,dep[u]=dep[fa[u]=f]+1;
  for (int v:lj[u]) if (v^f){
    dfs(v,u),sz[u]+=sz[v];
    if (sz[v]>sz[son[u]]) son[u]=v;
    }
  }
void dfs2(int u,int _top){
  top[u]=_top,ord[dfn[u]=++*top]=u;
  if (son[u]) dfs2(son[u],_top);
  for (int v:lj[u])
    if (v^fa[u]&&v^son[u]) dfs2(v,v);
  }
int qlca(int u,int v){
  for (;top[u]^top[v];)
    dep[top[u]]<dep[top[v]]?v=fa[top[v]]:u=fa[top[u]];
  return dep[u]<dep[v]?u:v;
  }
}

int main(){
int i,n=read();
for (i=1;i<n;++i){
  int u=read(),v=read();
  lj[v].push_back(u);
  lj[u].push_back(v);
  }
dfs(1,0),dfs2(1,1);
for (int q=read(),r,u,v;q--;){
  read(r),read(u),read(v);
  int lca[]={qlca(r,u),qlca(u,v),qlca(r,v)};
  sort(lca,lca+3,[&](int u,int v){return dep[u]>dep[v];});
  write(*lca),pl;
  }
}

谢谢大家.

猜你喜欢

转载自blog.csdn.net/qq_31908675/article/details/83006231