这个题很久以前就WA了,今天重写一个依然是WA。不知道是哪里错了,希望有人可以帮助debug一下。
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2021;
int n, m, q;
map<string, int> id;
string di[maxn];
vector<int> G[maxn];
int depth[maxn], fa[maxn], in[maxn];
char a[maxn], b[maxn];
int pre[maxn];
int find(int x) {
return x == pre[x] ? x : pre[x] = find(pre[x]);
}
void unite(int x, int y) {
x = find(x);
y = find(y);
if(x != y) pre[x] = y;
}
void dfs(int u, int p, int d) {
depth[u] = d;
fa[u] = p;
for(int i = 0; i < G[u].size(); i++) {
int &v = G[u][i];
if(v == u || v == p) continue;
dfs(v, u, d+1);
}
}
int query(int u, int v) {
if(find(u) != find(v)) return -1;
if(depth[u] < depth[v]) swap(u, v);
while(depth[u] > depth[v]) u = fa[u];
while(u != v) {
u = fa[u];
v = fa[v];
}
return u;
}
int main() {
// freopen("in", "r", stdin);
while(~scanf("%d", &n)) {
id.clear(); m = 0;
memset(depth, 0, sizeof(depth));
memset(in, 0, sizeof(in));
for(int i = 0; i < maxn; i++) {
pre[i] = i;
G[i].clear();
}
for(int i = 0; i < n; i++) {
scanf("%s %s", a, b);
if(id.find(a) == id.end()) {
id[a] = ++m;
di[m] = a;
}
if(id.find(b) == id.end()) {
id[b] = ++m;
di[m] = b;
}
G[id[a]].push_back(id[b]);
unite(id[a], id[b]);
in[id[b]]++;
}
for(int i = 1; i <= m; i++) {
if(!in[i]) {
dfs(i, -1, 1);
}
}
scanf("%d", &q);
while(q--) {
scanf("%s %s", a, b);
if(strcmp(a, b) == 0) {
puts(a);
continue;
}
if(id.find(a) == id.end() || id.find(b) == id.end()) {
puts("-1");
continue;
}
int ret = query(id[a], id[b]);
if(ret == -1) puts("-1");
else puts(di[ret].c_str());
}
}
return 0;
}
哇特判掉strcmp(a,b)==0就可以了,这个strick简直了。。。非常感谢