树上找任意两点的最近公共祖先,模板题
手写模板无压力、、、就是用了一下午
求LCA的具体步骤:
1:对树从根节点深搜,对每条深搜到达的边的顶点,记录深度(l数组记录)和搜索的的序号(就是这个点是第几个搜索到的,e数组记录)
2:记录每个节点在e数组中第一次出现的位置(r数组记录)
3:对于每次询问的两个点(a,b),从r数组得到这两点最先访问到的顺序,假设r[a]=lx,r[b]=ly,并且lx<ly(如果lx>ly,swap(a,b))。
4:这样在l数组中,在区间[lx,ly]深度最小的那个节点就是a和b的最近公共祖先了
4.1:对于求给定数组区间的最小/大值问题,转化为RMQ问题,令dp[i][j]表示数组中从第i位数开始,长度为2的j次方的长度序列中最小/大值
dp[i][j]=min(dp[i][j-1],dp[i+(1<<(j-1))-1][j-1])
4.2:由于题目要求数组的最近公共祖先节点的编号,而不是节点的深度,所以增加一个数组res.
res[i][j]表示在l数组中从第i位开始的长度为2的j次方的序列中深度最小的节点编号,得到res数组的过程跟随生成dp数组的一起。
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <vector>
#define M(a) memset(a,0,sizeof(a))
#define MM(a,b) memset(a,b,sizeof(a))
#define zout cout
#define INF 100000000
#define maxn 13000
using namespace std;
vector<int> g[maxn];
//tree
int r[maxn];
int e[maxn*2];
int l[maxn*2];
int dp[maxn*2][20];
int res[maxn*2][20];
bool vis[maxn];
int ei;
int n,m;
int root,x,y;
bool init()
{
char c;
int ic;
if(scanf("%d",&n)!=EOF)
{
M(vis);
for(int i=1; i<=n; i++)
{
g[i].clear();
}
for(int i=1; i<=n; i++)
{
scanf("%d",&x);
while(1)
{
c=getchar();
if(c=='(')break;
}
scanf("%d",&ic);
while(1)
{
c=getchar();
if(c==')')break;
}
for(int i=0; i<ic; i++)
{
scanf("%d",&y);
g[x].push_back(y);
vis[y]=1;
}
}
for(int i=1; i<=n; i++)
{
if(!vis[i])
{
root=i;
break;
}
}
return true;
}
return false;
}
void dfs(int u,int dep)
{
vis[u]=1;
e[ei]=u;
l[ei]=dep;
r[u]=ei;
ei++;
int v,vlen=g[u].size();
for(int i=0; i<vlen; i++)
{
v=g[u][i];
if(!vis[v])
{
dfs(v,dep+1);
e[ei]=u;
l[ei]=dep;
ei++;
}
}
}
void RMQ_init()
{
for(int i=0; i<ei; i++)
{
dp[i][0]=l[i];
res[i][0]=e[i];
}
for(int j=1; (1<<j)-1<ei; j++)
{
for(int i=0; i+(1<<j)<ei; i++)
{
x=dp[i][j-1];
y=dp[i+(1<<(j-1))][j-1];
if(x<y)
{
dp[i][j]=x;
res[i][j]=res[i][j-1];
}
else
{
dp[i][j]=y;
res[i][j]=res[i+(1<<(j-1))][j-1];
}
}
}
}
int RMQ(int lx,int ly)
{
int len=0;
while(lx+(1<<(len+1))-1<=ly)len++;
x=dp[lx][len];
y=dp[ly-(1<<len)+1][len];
if(x<y)return res[lx][len];
else return res[ly-(1<<len)+1][len];
}
int ans[maxn];
void solve()
{
char c;
M(vis);
ei=0;
dfs(root,1);
RMQ_init();
int a,b;
scanf("%d",&m);
memset(ans,0,sizeof(ans));
for(int i=0; i<m; i++)
{
while(1)
{
c=getchar();
if(c=='(')break;
}
scanf("%d%d",&a,&b);
while(1)
{
c=getchar();
if(c==')')break;
}
if(r[a]>r[b])swap(a,b);
ans[RMQ(r[a],r[b])]++;
}
for(int i=1; i<=n; i++)
{
if(ans[i])
printf("%d:%d\n",i,ans[i]);
}
}
int main()
{
freopen("1470.txt","r",stdin);
while(init())
{
solve();
}
return 0;
}