1. 程式人生 > >hihoCoder week13 最近公共祖先·一

hihoCoder week13 最近公共祖先·一

祖先 () 搜索 另一個 get div end ace n)

用的dfs,自下往上搜索一個節點的所有祖先,然後在相應祖先 判斷是否是另一個節點的祖先,如果是 就截止,否則繼續往上搜索,直到搜索到,或者知道所有的祖先都被掃描完成

#include <bits/stdc++.h>
using namespace std;
const int N = 1e3+10;

int n;
int cnt, tot;
map<string ,int> mp;
string s[N];

vector<int> son[N], fa[N];
string s1, s2;

int getId(string str)
{
    
if(mp[str]) { return mp[str]; } mp[str] = (++cnt); s[cnt] = str; return cnt; } int dfs(int u, int v) { if(u == v) return true; for(int i=0; i<son[u].size(); i++) { int x = son[u][i]; //cout << s[x] <<" "; if(dfs(son[u][i], v)) {
return true; } } //cout<<"\n"; return false; } int main() { freopen("in.txt","r",stdin); scanf("%d", &n); for(int i=1; i<=n; i++) { cin >> s1 >> s2; int u = getId(s1); int v = getId(s2); son[u].push_back(v); fa[v].push_back(u); }
int m; scanf("%d",&m); while(m--) { cin >> s1 >> s2; int u = getId(s1); int v = getId(s2); // cout <<u <<" "<< v<<"\n"; bool flag=0; queue<int> que; que.push(u); while(!que.empty()) { int tmp=que.front(); que.pop(); //cout << s[tmp]<<"\n"; for(int i=0; i<fa[tmp].size(); i++) { que.push(fa[tmp][i]); } if(dfs(tmp,v)) { flag = true; cout << s[tmp] <<endl; break; } } if(!flag) puts("-1"); } return 0; }

hihoCoder week13 最近公共祖先·一