hihoCoder 1069 最近公共祖先·三



#include <bits/stdc++.h>
using namespace std;

map<string,int> nameMap;
string names[100005];

struct node{
	int pa;
	vector<int> son;
	vector<pair<int,int> > qu;
	node() : pa(-1){}
}no[100005];
int ans[100005];


int findset(int x){
    if(x != no[x].pa)
        no[x].pa = findset(no[x].pa);
    return no[x].pa;
}

void dfs(int f){
	no[f].pa = f;
    int len = no[f].son.size();
	for(int i=0 ;i<len;i++){
		int index = no[f].son[i];
		dfs(index);
		no[index].pa  = f;
	}
	int qlen = no[f].qu.size();
	for(int i=0; i<qlen; i++){
		pair<int, int> p = no[f].qu[i];
		if(no[p.first].pa != -1)
			ans[p.second] = findset(p.first);
	}
}

int main(){
	int N,M;
	scanf("%d",&N);
	for(int i=0; i<N; i++){
		string fa,son;
		cin>>fa>>son;
		if(nameMap.find(fa) == nameMap.end())
			nameMap[fa] = nameMap.size();
		if(nameMap.find(son) == nameMap.end())
			nameMap[son] = nameMap.size();
		int nf = nameMap[fa], ns = nameMap[son];
		names[nf] = fa;
		names[ns] = son;
		no[nf].son.push_back(ns);
	}
	scanf("%d",&M);
	for(int i=0; i<M; i++){
		string qu1,qu2;
		cin>>qu1>>qu2;
		int n1 = nameMap[qu1], n2 = nameMap[qu2];
		no[n1].qu.push_back(make_pair(n2,i));
		no[n2].qu.push_back(make_pair(n1,i));
	}
	dfs(1);
	for(int i = 0; i < M ; i++)
		//puts(names[ans[i]].c_str());
		cout<<names[ans[i]]<<endl;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值