您的位置:首页 > 其它

HIHO #1062 : 最近公共祖先·一

2016-08-09 18:01 381 查看
题目链接

题目数据小直接暴力计算

小坑点:a==b 的时候输出a就好了

#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<string>
#include<cmath>
#include<queue>
#include<map>
#include<set>
#include<cstdlib>
#include<vector>
using namespace std;
#define cl(a,b) memset(a,b,sizeof(a))
#define LL long long
#define pb push_back
#define gcd __gcd

#define For(i,j,k) for(int i=(j);i<k;i++)
#define lowbit(i) (i&(-i))
#define _(x) printf("%d\n",x)

const int maxn = 2e6+10;
const int inf  = 1 << 28;

int id;
map<string,int> mp;
int getid(string s){
if(!mp.count(s))return mp[s]=id++;
return mp[s];
}
map<int,string> tos;

int f[maxn];

vector<int> v;

int main(){
id = 1;
int n,m;
scanf("%d",&n);
cl(f,-1);
for(int i=0;i<n;i++){
string a,b;
cin>>a>>b;
int ida = getid(a);
int idb = getid(b);
tos[ida] = a;
tos[idb] = b;
f[idb] = ida;
}

scanf("%d",&m);
while(m--){
string a,b;cin>>a>>b;

int ida = getid(a);
int idb = getid(b);

if(a==b){
cout<<a<<endl;continue;
}

v.clear();

while(ida!=-1){
v.pb(ida);
ida = f[ida];
}
int ans = -1;

while(idb!=-1){
for(int i=0;i<v.size();i++){
if(v[i]==idb){
ans = idb;break;
}
}
if(ans!=-1)break;
idb = f[idb];
}
if(ans==-1){
puts("-1");continue;
}
cout<<tos[ans]<<endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: