它上面讲的很详细。
http://hihocoder.com/problemset/problem/1067?sid=210395
#include<iostream> #include<cstdio> #include<cstring> #include<map> #include<vector> using namespace std; const int maxn = 111111; int father[maxn]; struct Node { int next; int to; }e[maxn * 2]; int len; int head[maxn]; int color[maxn]; int l[maxn]; int r[maxn]; map<pair<int, int>, int> ans; vector<int> q[maxn]; int getfather(int x) { if (x != father[x]) father[x] = getfather(father[x]); return father[x]; } void un(int a, int b) { int fa = getfather(a); int fb = getfather(b); father[fb] = fa; } void add(int from, int to) { e[len].to = to; e[len].next = head[from]; head[from] = len++; } void dfs(int x) { for (int i = head[x]; i != -1; i = e[i].next){ int cc = e[i].to; dfs(cc); un(x, cc); } color[x] = 1; for (int i = 0; i < q[x].size(); i++){ int t = q[x][i]; if (color[t]){ ans[make_pair(x, t)] = getfather(t); ans[make_pair(t, x)] = getfather(t); } } } int main() { string a, b; int n; map<string, int> m; map<int, string> m1; cin >> n; int k; int sum = 1; len = 0; memset(head, -1, sizeof(head)); for (int i = 0; i < n; i++){ cin >> a >> b; int c; int d; if (!m.count(a)) m[a] = sum, m1[sum] = a, sum++; if (!m.count(b)) m[b] = sum, m1[sum] = b, sum++; c = m[a]; d = m[b]; add(c, d); } for (int i = 0; i<maxn; i++) father[i] = i; cin >> k; for (int i = 0; i < k; i++){ cin >> a >> b; int c = m[a]; int d = m[b]; l[i] = c; r[i] = d; q[c].push_back(d); q[d].push_back(c); } memset(color, 0, sizeof(color)); dfs(1); for (int i = 0; i < k; i++){ cout<<m1[ans[make_pair(l[i],r[i])]]<<endl; } return 0; }