跳到正文

题解

题解:P3379 【模板】最近公共祖先(LCA)

_zyx2012约 14 分钟
原文

这是 2026年6月1日 存档的第 2 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年5月4日
收录
2026年5月4日
更新
2026年11月11日
篇幅
约 14 分钟
获赞
2
题目
P3379

版本

  1. v3当前
  2. v2
  3. v1

这里使用一种新型 LCA 求法。

虽然有亿点点复杂,但是至少速度完虐倍增。

先定义以下内容:

  • LCA⁡(x,y)\operatorname{LCA}(x,y):xx 和 yy 的 LCA。
  • szxsz_x:xx 的子树大小。
  • atxat_x:xx 在 dfs 序中所处的位置。
  • fxf_x:xx 的父亲节点,其中根节点的 fxf_x 被定义为 00。
  • toxto_x:xx 的祖先中最深的点 yy 满足 szx×2≤ysz_x \times 2 \leq y。

预处理

sz,f,atsz,f,at 很好维护。

但是这个 toto 怎么搞?

先定义 uu 的重儿子为 uu 的儿子中子树大小最大的,其余的儿子被定义为轻儿子,重子树为重儿子的子树,轻子树为轻儿子的子树(其实就是重剖的定义)。

那么如果我们把每个点 uu 的重儿子求出来,则所有轻儿子中所有点 vv 满足 tovto_v 还没有被确定,其 tovto_v 都被确定为 uu。

然后就得到了一个性质:任选一个子树,它的轻儿子中都不可能存在任何一个点 xx 满足 toxto_x 不在该子树中。

反复使用这个结论,我们会发现:任意一颗树中,一定能找到一个点 xx,使得 xx 到根的路径上所有点组成的点集恰好为这棵树中所有满足 tou=0to_u=0 的点 uu 所组成的点集。

那么重子树中没有找到 toto 的点就可以暴力去找。

具体实现:

C++
	vector<int> sz(n + 1),to(n + 1),at(n + 1),f(n + 1);
	int dftop = 0;

	auto dfs = [&](auto &&self,int x,int y) -> int {
		f[x] = y;
		sz[x] = 1;
		at[x] = ++dftop;//更新f、sz、at

		int mxsz = 0,vv = x;

		for (auto &i:a[x])
			if (i != y){
				int v = self(self,i,x);
				sz[x] += sz[i];//更新sz

				if (sz[i] > mxsz)
                    mxsz = sz[i],swap(vv,v);//重儿子是最后被更新的,如果重儿子由之前确认的点u变成i,则把u按照轻儿子的方式处理并把重儿子设置为i,否则把i按照轻儿子的方式处理。

				for (;v != x;v = f[v])
					to[v] = x;
			}

		for (;sz[vv] * 2 <= sz[x];vv = f[vv]) to[vv] = x;//处理重儿子

		return vv;
	};

查询

重复执行以下过程:

  1. 如果 szu>szvsz_u \gt sz_v,交换 u,vu,v。
  2. 如果 atv≤atu<atv+szvat_v \leq at_u \lt at_v + sz_v,也就是说 vv 是 uu 的祖先,结束。
  3. 如果 uu 不是 vv 的祖先且 vv 不是 uu 的祖先,且 szu≤szvsz_u \leq sz_v,则有: szLCA⁡(u,v)≥szu+szv+1sz_{\operatorname{LCA}(u,v)} \geq sz_u+sz_v+1 szLCA⁡(u,v)≥szu+szu+1sz_{\operatorname{LCA}(u,v)} \geq sz_u+sz_u+1 szLCA⁡(u,v)≥2×szu+1sz_{\operatorname{LCA}(u,v)} \geq 2 \times sz_u+1 szLCA⁡(u,v)≥2×szusz_{\operatorname{LCA}(u,v)} \geq 2 \times sz_u 根据 toto 的定义,可以发现 touto_u 的深度不会低于 LCA⁡(u,v)\operatorname{LCA}(u,v),那么我们令 u′=touu' = to_u,会发现 LCA⁡(u,v)=LCA⁡(u′,v)\operatorname{LCA}(u,v)=\operatorname{LCA}(u',v),那么我们就可以直接令 u←u′u \gets u'。

结束后 vv 就是 LCA。

Code

C++
#include <iostream>
#include <climits>
#include <vector>
using namespace std;

namespace io{
#ifdef LOCAL
	constexpr int len = 1;
#else
	constexpr int len = 1 << 21;
#endif
	class input{
		char buf[len],*bg = buf,*en = buf;
	public:
		inline char gc(){
			return (bg == en&&(en = (bg = buf) + fread(buf,1,len,stdin)) == buf?EOF:*(bg++));
		}

		template<class T>inline void getuint(T &v){
			v = 0;
			char ch,ch2;

			for (;(ch = gc()) < '0'||ch > '9'&&ch != EOF;);

			for (;ch >= '0'&&ch <= '9';ch = gc()) v = (v << 1) + (v << 3) + ch - 48;
		}

		template<class T>inline void getint(T &v){
			v = 0;
			char ch,ch2;
			bool op = 0;

			for (;(ch = gc()) < '0'||ch > '9'&&ch != EOF;) op ^= (ch == '-');

			for (;ch >= '0'&&ch <= '9';ch = gc()) v = (v << 1) + (v << 3) + ch - 48;

			if (op) v = -v;
		}

		template<class T>inline T getint(){
			T ret = 0;
			getint(ret);
			return ret;
		}

		template<class T>inline T getuint(){
			T ret = 0;
			getuint(ret);
			return ret;
		}

		inline int getstr(char *s,int len = INT_MAX){
			int cnt = 0;
			for (;--len&&(*s = gc()) != ' '&&*s != '\n';cnt++,s++);
			*s = '\0';
			return cnt;
		}

		inline void getstr(string &s){
			s.clear();
			for (char ch;(ch = gc()) != ' '&&ch != '\n';s += ch);
		}

		inline input &operator >> (short &x){getint(x);return *this;}
		inline input &operator >> (int &x){getint(x);return *this;}
		inline input &operator >> (long &x){getint(x);return *this;}
		inline input &operator >> (long long &x){getint(x);return *this;}
		inline input &operator >> (__int128 &x){getint(x);return *this;}
		inline input &operator >> (unsigned short &x){getint(x);return *this;}
		inline input &operator >> (unsigned &x){getint(x);return *this;}
		inline input &operator >> (unsigned long &x){getint(x);return *this;}
		inline input &operator >> (unsigned long long &x){getint(x);return *this;}
		inline input &operator >> (unsigned __int128 &x){getint(x);return *this;}
		inline input &operator >> (char &x){for (;(x = gc()) == ' '||x == '\n';);return *this;}
		inline input &operator >> (char *x){getstr(x);return *this;}
		inline input &operator >> (string &x){getstr(x);return *this;}
	}fin;

	class output{
		char buf[1 << 21],buf2[20],mp[1000][3];
		int top = 0,top2 = 0;
	public:
		output(){
			for (int i = 0,ci = 48;i < 1000;i += 100,ci++)
				for (int j = 0,cj = 48;j < 100;j += 10,cj++)
					for (int k = 0,ck = 48;k < 10;k++,ck++)
						mp[i + j + k][0] = ck,mp[i + j + k][1] = cj,mp[i + j + k][2] = ci;
		}
		inline void flush(){
			fwrite(buf,1,top,stdout);
			top = 0;
		}

		inline void pc(char ch){buf[top++] = ch;if (top >= 1 << 21) flush();}

		template<class T>inline void putint(T x){
			if (!x){pc('0');return ;}
			if (x < 0) pc('-'),x = -x;
			for (;x >= 1000;x /= 1000)
				buf2[top2++] = mp[x % 1000][0],buf2[top2++] = mp[x % 1000][1],buf2[top2++] = mp[x % 1000][2];
			if (x){
				buf2[top2++] = mp[x][0];
				if (x >= 10){
					buf2[top2++] = mp[x][1];
					if (x >= 100)
						buf2[top2++] = mp[x][2];
				}
			}
			for (;top2;pc(buf2[--top2]));
		}

		inline void putstr(const char *s,int len){
			for (;len--;pc(*(s++)));
		}

		inline void putstr(const string &s){
			for (auto i:s) pc(i);
		}

		inline output &operator << (short x){putint(x);return *this;}
		inline output &operator << (int x){putint(x);return *this;}
		inline output &operator << (long x){putint(x);return *this;}
		inline output &operator << (long long x){putint(x);return *this;}
		inline output &operator << (const __int128 &x){putint(x);return *this;}
		inline output &operator << (unsigned short x){putint(x);return *this;}
		inline output &operator << (unsigned int x){putint(x);return *this;}
		inline output &operator << (unsigned long x){putint(x);return *this;}
		inline output &operator << (unsigned long long x){putint(x);return *this;}
		inline output &operator << (const unsigned __int128 &x){putint(x);return *this;}
		inline output &operator << (char x){pc(x);return *this;}
		inline output &operator << (const char *x){putstr(x);return *this;}
		inline output &operator << (const string &x){putstr(x);return *this;}
		inline output &operator << (void (*func)(output &)){func(*this);return *this;}

		~output(){flush();}
	}fout;

	void flush(output &out){out.flush();}
	void endl(output &out){out << '\n';out.flush();}
}

using namespace io;

int n = fin.getuint<int>();
vector<vector<int>> a(n + 1);

struct info{
	int hson,sz,to,d,f,dto;
};

vector<info> nd(n + 1);
vector<int> dfn(n);
int top = -1;

void dfs(int x){
	dfn[++top] = x;
	nd[x].sz = 1;
	nd[x].dto = nd[x].d;

	nd[x].to = x;
	for (auto i:a[x]){
        if (i == nd[x].f) continue;
        nd[i].f = x;
        
		nd[i].d = nd[x].d + 1;
		dfs(i);
		nd[x].sz += nd[i].sz;

		if (nd[i].sz > nd[nd[x].hson].sz)
			nd[x].hson = i;
	}
}

int main (){
    int m,s;
	fin >> m >> s;

	for (int i = n;--i;){
		int x,y;
		fin >> x >> y;
		a[x].push_back(y);
        a[y].push_back(x);
	}

	dfs(s);
	for (auto x:dfn)
		nd[nd[x].hson].to = nd[x].to,nd[nd[x].hson].dto = nd[x].dto;

	for (;m--;){
		int x,y;
		fin >> x >> y;

		for (;nd[x].to != nd[y].to;){
			if (nd[x].dto < nd[y].dto){int v = x;x = y;y = v;}
			x = nd[nd[x].to].f;
		}

		fout << (nd[x].d < nd[y].d?x:y) << '\n';
	}
}