Tree chain division to find LCA [template] super detailed explanation + code


(off-topic)

Although LCA is not the fastest tree chain division (listen to lzw boss say that LCT is faster), but because I want to learn, I study hard.

Because those on the Internet are all piecemeal, I finally understand it through patchwork and understanding.

Then I will repeat it with my own understanding~ It can be said that it is full of money to teach~

(Main article)

For the concept of tree chain segmentation, please poke into this article ~

The principle is specifically explained in the program~

For details , please  click here

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int MAX=500005;
struct Edge //adjacency list
{
	int to,next;
}edge[MAX << 1];


int fa[MAX],     top[MAX],   deep[MAX], size[MAX],      son[MAX];
  //The heavy son of the number of sub-tree nodes (respectively)
int first[MAX],tot;
void add(int i,int j)
{ //The adjacency list stores the undirected graph~
	edge[++tot].to = j;
	edge[tot].next = first[i];
	first[i] = tot;
}


void dfs1(int p) //p current node
{ //The first dfs, used to find the parent node & depth & number of child nodes & heavy nodes of all nodes
	size[p] = 1; //The number of p child nodes is initialized and counted because it is used to return to the last layer so that its father can get the exact number of child nodes
	deep[p] = deep[fa[p]]+1; //Define the depth of point p (its father+1)
	  for (int a = first[p]; a; a = edge[a].next)
	  { // Traverse all nodes connected to point p
	  	int b = edge[a].to; //The point that p reaches through an edge connected to it (too lazy to type so use a variable instead)
	  	  if (b == fa[p]) continue; //If you accidentally connect to the parent node of p, do not process and continue to the next point
	  	fa[b] = p; //Before dfs is required, determine the parent node of the next node. If the external memory is placed, it will be doubled several times.
		dfs1(b);
		size[p]+=size[b]; //Count the number of child nodes of the current node
	  	  if (size[b] > size[son[p]]/* || !son[p] (can be omitted because the previous item has been included)*/) son[p] = b;
	  } //(The previous line) If the child node of p's child node b is greater than the original heavy child of p || No over-heavy node is set (can be omitted, see the next explanation)
} //Because son[p] is 0 when it is not set size[0] is initially defined as 0 size[b] Since the deep search is definitely greater than 0


void dfs2(int p,int father) //p current node father The starting point of the chain where the current node is located
{ //The second dfs finds the starting point of the chain where each node is located (see later)
	top[p] = father; //Describe the chain start point of the current node as father
	  if (!son[p]) return; // don't process if p is not on the heavy chain
	dfs2(son[p],father); //Remember the starting point father of the point on the same heavy chain
	  for (int a = first[p]; a; a = edge[a].next)
	  { // Traverse all nodes connected to point p
	  	int b = edge[a].to; //The point that p reaches through an edge connected to it (too lazy to type so I also use the same variable instead)
	  	//(Down) If b is not a heavy child node of p & is not a parent node of p, set its vertex as its own recursive new heavy chain
	  	  if (b != son[p] && b != fa[p]) dfs2(b,b);
	  } //(Upstream supplement) The new heavy chain is to continue searching from its vertex after finding the light chain, and all of them must be found
}


intmain()
{
	int n,m,g,i,j;
	scanf("%d%d%d",&n,&m,&g);
	  for (int a = 1; a < n; a++)
	  { //Enter the edge adjacency list connecting two nodes here and store the undirected graph here
	  	scanf("%d%d",&i,&j);
	  	add(i,j);
		add(j,i); //Key point
	  }
	dfs1(g); //First deep search
	dfs2(g,g); //Second deep search
	  for (int a = 1; a <= m; a++)
	  { //The nearest common ancestor of i and j is queried here
	  	scanf("%d%d",&i,&j);
	  	  while (top[i] != top[j]) //if i and j have different chain start points then
	  	  { //If the depth of the starting point of the respective chains of i and j is different, modify the deep one first
	  	    if (deep[top[i]] < deep[top[j]]) j = fa[top[j]];
	  	    else i = fa[top[i]]; //Connect the vertex of the node to be modified to the vertex of the parent node of the point (maybe not quite right)
	  	  } //Only one can be modified at a time, otherwise two points may pass by if they are modified together
	  	  if (deep[i] > deep[j]) printf("%d\n",j);
	  	  else printf("%d\n",i);
	  } //The two points are on the same chain at this time. Because it is looking for the nearest common ancestor, the point with a smaller depth is output
	return 0; //(Upstream explanation) Because the point with a larger depth has to go up to meet the point with a smaller depth
}

It's probably like this. I think it's fried chicken. OvO

It took 1344ms to pass the template question, which is still relatively slow =-=

Then add random optimization (don't look =-=)

#define r register
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int MAX=1 << 19;
struct Edge
{
	int to,next;
}edge[MAX << 1];
int fa[MAX],top[MAX],deep[MAX],size[MAX],son[MAX],first[MAX],tot;
inline void read(int &x)
{
    char q = getchar();x = 0;
    	while (q < '0' || q > '9') q = getchar();
    	while (q <= '9' && q >= '0')
	x = (x << 1) + (x << 3) + q - (3 << 4), q = getchar();
}
void writeln(int x)  
{
    tot = 0; char q [8];
    	while (x) q[++tot] = (x%10) + (3 << 4), x /= 10;
    	while (tot) putchar(q[tot--]);
    putchar('\n');
}
void add(r int x,r int y)
{
    edge[++tot].to = y;
    edge[tot].next = first[x];
    first[x] = tot;
}
void dfs1(int p)
{
    ++size[p];deep[p] = deep[fa[p]]+1;
    	for (r int a = first[p]; a; a = edge[a].next)
    	{
      		r int b = edge[a].to;
      		if (b == fa[p]) continue;
      		fa[b] = p;dfs1(b);size[p]+=size[b];
      		if (size[b] > size[son[p]]) son[p] = b;
    	}
}
void dfs2(int p,int father)
{
    top[p] = father;
    	if (son[p]) dfs2(son[p],father);
    	for (r int a = first[p]; a; a = edge[a].next)
    	{
    		r int b = edge[a].to;
    		if (b != son[p] && b != fa[p]) dfs2(b,b);
    	}
}
intmain()
{
    r int i,j,m;
    int n,g;
    read(n);read(m);read(g);
    	for (r int a = 1; a < n; a++)
    	{
    		read(i);read(j);
    		add(i,j);add(j,i);
    	}
    dfs1(g);
    dfs2(g,g);
      while (m--)
      {
      	read(i);read(j);
      		while (top[i] != top[j])
				if (deep[top[i]] < deep[top[j]]) j = fa[top[j]];
      			else i = fa[top[i]];
      		if (deep[i] > deep[j]) writeln(j);
      		else writeln(i);
      }
    return 0;
}
1140ms=-= not much use

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324526223&siteId=291194637