最近公共祖先LCA离线算法

    引用 hihocoder 题

   离线处理询问,在线算法也可以解决这个,不过是先建立树。

 而离线算法则是染色节点,加并查集实现。

链接:http://hihocoder.com/problemset/problem/1067

上面有详细的解释。

代码:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<map>
#include<vector>
using namespace std;
const int max_n=5+1e5;
map<string,int > Namenum;
map<int,string> numName;
vector<int> G[max_n];
vector<int> Q[max_n];
string q1[max_n],q2[max_n],ans[max_n];
int fa[max_n];
int cnt=0;
int getnum(string s)
{
        if(Namenum[s]==0)
        {
                 Namenum[s]=(++cnt);
                 numName[cnt]=s;
        }
        return Namenum[s];
}
int Find(int u){
  return fa[u]==u?u:fa[u]=Find(fa[u]);
}
void LCA(int u,int ac)
{
         fa[u]=u;
         for(int i=0;i<G[u].size();i++)
                 LCA(G[u][i],u);
         for(int i=0;i<Q[u].size();i++)
         {
                  int index=Q[u][i];
                  int w=Namenum[q1[index]]==u?Namenum[q2[index]]:Namenum[q1[index]];
                  if(fa[w]==-1) continue;
                  ans[index]=numName[Find(fa[w])];
         }
         fa[u]=Find(fa[ac]);
}
int main()
{
         //freopen("in.txt","r",stdin);
         int n,m;
         cin>>n;
         string u,v;
        // Namenum.clear(),numName.clear();
         for(int i=0;i<n;i++)
         {
                cin>>u>>v;
                int x=getnum(u),y=getnum(v);
                G[x].push_back(y);
         }
         cin>>m;
         for(int i=0;i<m;i++)
         {
                  cin>>q1[i]>>q2[i];
                  Q[Namenum[q1[i]]].push_back(i);
                  Q[Namenum[q2[i]]].push_back(i);
         }
         memset(fa,-1,sizeof(fa));
         fa[0]=0;
         LCA(1,0);
         for(int i=0;i<m;i++)
                cout<<ans[i]<<endl;
         return 0;
}

另外一种写法:

  代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <map>

using namespace std;

const int N = 100005;
const int M = 200005;

int n, m;
int tot, head[N], to[N], next[N];
int tot1, head1[N], to1[M], id[M], next1[M];
int fa[N], ans[N];
char name[100005][100], name1[100], name2[100];
bool visit[N];
map <string, int> ns;

void addEdge(const int& u, const int& v) {
	to[tot] = v;
	next[tot] = head[u];
	head[u] = tot++;
}

void addEdge1(const int& u, const int& v, const int& i) {
	to1[tot1] = v;
	id[tot1] = i;
	next1[tot1] = head1[u];
	head1[u] = tot1++;
}

void addDoubleEdge(const int& u, const int& v, const int& i) {
	addEdge1(u, v, i), addEdge1(v, u, i);
}

int find(const int& u) {
	return fa[u] < 0 ? u : (fa[u] = find(fa[u]));
}

void tarjan(const int& u) {
	visit[u] = true;
	fa[u] = -1;
	for (int i = head[u]; i != -1; i = next[i]) {
		int v = to[i];
		tarjan(v);
		fa[v] = u;
	}

	for (int i = head1[u]; i != -1; i = next1[i]) {
		int v = to1[i];
		if (visit[v])
			ans[id[i]] = find(v);
	}
}

int main()
{
	while (scanf("%d", &n) != EOF) {
		memset(head, -1, sizeof(head));
		memset(head1, -1, sizeof(head1));
		tot = tot1 = 0;
		ns.clear();
		int cnt = 0;
		for (int i = 0; i < n; ++i) {
			scanf("%s %s", name1, name2);
			string fa(name1), son(name2);
			if (ns.find(fa) == ns.end())
				strcpy(name[cnt], name1), ns[fa] = cnt++;
			if (ns.find(son) == ns.end())
				strcpy(name[cnt], name2), ns[son] = cnt++;
			addEdge(ns[fa], ns[son]);
		}
		scanf("%d", &m);
		for (int i = 0; i < m; ++i) {
			scanf("%s %s", name1, name2);
			string fa(name1), son(name2);
			addDoubleEdge(ns[fa], ns[son], i);
		}
		memset(visit, false, sizeof(visit));
		tarjan(0);
		for (int i = 0; i < m; ++i)
			printf("%s\n", name[ans[i]]);
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Tarjan算法是一种用于求解最近公共祖(Least Common Ancestors,LCA)问题的离线算法算法的核心思想是利用深度优先搜索(DFS)和并查集(Union Find)来解决问题。 首先,我们从根节点开始遍历每一个节点,并将节点分为三类,用st[]数组表示。0代表还未被遍历,1代表正在遍历这个点,2代表已经遍历完这个点并且回溯回来了。这样的划分有助于确定节点的最近公共祖先。 在Tarjan算法中,我们一边遍历一边回应查询。每当遍历到一个节点时,我们查找与该节点相关的所有查询。如果查询中的节点已经被遍历完(即st[]值为2),我们可以利用已经计算好的信息来计算它们的最近公共祖先最近公共祖先的距离可以通过两个节点到根节点的距离之和减去最近公共祖先节点到根节点的距离来计算。 在Tarjan算法中,我们可以通过深度优先搜索来计算dist[]数组,该数组表示每个节点到根节点的距离。我们可以利用父节点到根节点的距离加上边的权值来计算每个节点到根节点的距离。 最后,我们可以通过并查集来操作st[]数组。当遍历完一个节点的所有子树后,将子树中的节点放入该节点所在的集合。这样,每个子树的节点的最近公共祖先都是该节点。 综上所述,Tarjan算法利用DFS和并查集来求解最近公共祖先问题。它的时间复杂度为O(n+m),其中n是节点数,m是查询次数。通过该算法,我们可以高效地解决最近公共祖先的问题。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [最近公共祖先tarjan](https://blog.csdn.net/qq_63092029/article/details/127737575)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [【模版】Tarjan离线算法最近公共祖先(LCA)](https://blog.csdn.net/weixin_43359312/article/details/100823178)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [Tarjan算法求解最近公共祖先问题](https://blog.csdn.net/Yeluorag/article/details/48223375)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值