因为输入均为名字,所以选择map将string映射为int,之后用前向星大法存储整棵树,并且用father数组记录父节点,用name数组记录所有名字,之后输入查询,对于每个查询,先将名字映射为int,然后存入pair数组,按顺序,并且is数组判断此节点有无查询,利用前向星存储每个名字对应的另一个名字,直接执行LCA离线算法即可。
对于LCA离线算法,利用dfs对树进行染色,第一次经过的节点染灰色,第二次也就是离开的时候染黑色,那么不断深搜的过程中,若当前节点为查询的一个节点a,则查看另一个节点b的颜色,可知共三种情况:
1.白色,暂时忽略
2.灰色,则两点对劲公共祖先为b
3.黑色,则两点最近公共祖先为距离b最近的灰色父节点。
对于第三种情况,我们可以用并查集将每次查询的时间复杂度从O(N)提升为O(1)(其实是Ackman函数的反函数),即每将一个节点染为黑色,就将此节点所在集合并入其父节点所在集合,初始每个节点一个集合,并由父节点代表词集合——即最近的最深的灰色父节点。
#include <iostream>
#include <map>
#include <string>
#include <cstdio>
using namespace std;
struct EDGE{
int to;
struct EDGE *next;
}e[100010];
struct EDGE* point1[100010]={0};
struct QUERY{
int brother;
struct QUERY *next;
}q[100010];
struct QUERY* qp[100010]={0};
int sq=0;
int color[100010]={0},sn=1,se=0;
map<string,int> h;
map<pair<int,int>,int> ans;
string name[100010];
pair<int,int> query[100010];
bool is[100010]={false};
int father[100010];
int SET[100010];
int gf(int x)
{
if(x==SET[x]) return x;
SET[x]=gf(SET[x]);
return SET[x];
}
void dfs(int root)
{
color[root]=1;
if(is[root]){
struct QUERY *t;
for(t=qp[root];t;t=t->next){
int v=t->brother;
if(color[v]==0) continue;
if(color[v]==1){
ans[make_pair(root,v)]=v;
ans[make_pair(v,root)]=v;
}
if(color[v]==2){
int temp=gf(v);
//while(color[temp]==2) temp=father[temp];
ans[make_pair(root,v)]=temp;
ans[make_pair(v,root)]=temp;
}
}
}
for(struct EDGE* son=point1[root];son;son=son->next){
int v=son->to;
dfs(v);
}
color[root]=2;
int fr=gf(root),ff=gf(father[root]);
SET[fr]=ff;
}
void addedge(int a,int b)
{
e[se].to=b;e[se].next=point1[a];
point1[a]=&e[se];se++;
}
void addquery(int a,int b)
{
q[sq].brother=b;q[sq].next=qp[a];
qp[a]=&q[sq];sq++;
}
int main()
{
//freopen("in.txt","r",stdin);
int n,end;
cin>>n;
end=(n<<1)>100000?100000:(n<<1);
for(int i=1;i<=end;i++) SET[i]=father[i]=i;
while(n--){
string a,b;
int pa,pb;
cin>>a>>b;
if(!h.count(a)){
h[a]=sn;
name[sn]=a;
sn++;
}
pa=h[a];
if(!h.count(b)){
h[b]=sn;
name[sn]=b;
sn++;
}
pb=h[b];
addedge(pa,pb);
father[pb]=pa;
}
int m;
cin>>m;
for(int i=1;i<=m;i++){
string a,b;
int pa,pb;
cin>>a>>b;
pa=h[a];pb=h[b];
query[i]=make_pair(pa,pb);
is[pa]=true;is[pb]=true;
addquery(pa,pb);
addquery(pb,pa);
}
int root=father[1];
while(root!=father[root]) root=father[root];
dfs(root);
for(int i=1;i<=m;i++) cout<<name[ans[query[i]]]<<endl;
return 0;
}