1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| #include <cstdio> #include <cstring> #include <algorithm> #include <vector> using namespace std;
const int MAXN = 10010;
int n, root; int indegree[MAXN]; int father[MAXN]; int ancestor[MAXN]; bool vis[MAXN];
vector<int> tree[MAXN]; vector<int> query[MAXN];
void init() { for(int i = 0; i < MAXN; i++){ father[i] = i; ancestor[i] = i; } memset(vis, false, sizeof(vis)); }
void inputTree() { scanf("%d", &n); for(int i = 0; i <= n; i++){ tree[i].clear(); indegree[i] = 0; } for(int i = 1; i < n; i++){ int x, y; scanf("%d%d", &x, &y); tree[x].push_back(y); indegree[y]++; } for(int i = 1; i <= n; i++)if(!indegree[i]){ root = i; break; } }
void inputQuery() { for(int i = 0; i < n; i++){ query[i].clear(); } int m; m = 1; while(m--){ int u, v; scanf("%d%d", &u, &v); query[u].push_back(v); query[v].push_back(u); } }
int finds(int x) { return x == father[x] ? father[x] : father[x] = finds(father[x]); }
void unions(int x, int y) { int root_x = finds(x); int root_y = finds(y); father[root_y] = root_x; }
void Tarjan(int x) { for(int i = 0; i < tree[x].size(); i++){ Tarjan(tree[x][i]); unions(x, tree[x][i]); ancestor[finds(x)] = x; } vis[x] = true; for(int i = 0; i < query[x].size(); i++){ if(vis[query[x][i]]){ printf("%d\n", ancestor[finds(query[x][i])]); } } }
int main() { int T; scanf("%d", &T); while(T--){ init(); inputTree(); inputQuery(); Tarjan(root); } return 0; }
|