hihoCoder 1062 最近公共祖先·一

本文详细介绍了如何使用C++实现寻找二叉树中两个节点的最近公共祖先的算法,包括输入输出流程、核心代码解析及实际应用案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近公共祖先·一

AC代码:

#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <map>
using namespace std;

int main()
{
	int N,M,id=0;
	scanf("%d",&N);
	vector<string> fa,son,names;
	map<string,int> m;
	for(int i = 0; i < N; i++) {
		string str1,str2;//str1父亲,str2孩子
		cin>>str1>>str2;
		fa.push_back(str1);
		son.push_back(str2);
		m[str1] = 0;m[str2] = 0;
	}
	for(map<string,int>::iterator it = m.begin(); it != m.end(); it++){
		names.push_back(it->first);
		it->second = id++;
	}
	vector<int> pa(id,-1);
	for(int i = 0; i < N; i++)
        pa[m[son[i]]] = m[fa[i]];
	scanf("%d",&M);
	for(int i = 0; i < M; i++){
		string str1,str2;
		cin>>str1>>str2;
		int a = -1,b = -1;
		if(m.count(str1))
            a = m[str1];
		if(m.count(str2))
            b = m[str2];

		if(a==-1 || b==-1){
			if(str1 == str2)
                cout<<str1<<endl;
			else
                printf("-1\n");
		}
		else{
            vector<int> mask(id,1);
			while(a>-1) {mask[a] = 0;a = pa[a];}
			while(b>-1 && mask[b]) b = pa[b];
			if(b>-1)
                //printf("%s\n",names[b].c_str());
                cout<<names[b]<<endl;
			else
                printf("-1\n");
		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值