#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <vector>
#include <stack>
#include <deque>
#include <queue>
#include <bitset>
#include <list>
#include <map>
#include <set>
#include <iterator>
#include <algorithm>
#include <functional>
#include <utility>
#include <sstream>
#include <climits>
#include <cassert>
#define MID(x,y) ( ( x + y ) >> 1 )
#define L(x) ( x << 1 )
#define R(x) ( x << 1 | 1 )
#define BUG puts("here!!!");
#define STOP system("pause");
using namespace std;
const int N = 10005;
vector<int> p[N];
int f[N], c[N];
int n;
void DFS(int u, int dep) {
c[u] = dep;
for(vector<int>::iterator it = p[u].begin(); it != p[u].end(); ++it) {
DFS(*it, dep+1); //
}
}
int main() {
int T;
cin >> T;
while(T--) {
cin >> n;
for(int i = 0; i < n; i++) p[i].clear();
memset(f, 255,sizeof(f));
int x, y;
for(int i = 0; i < n-1; i++) {
scanf("%d%d", &x, &y);
p[x-1].push_back(y-1);
f[y-1] = x-1;
}
for(int i = 0; ; i++) {
if(f[i] < 0) {
DFS(i, 0);
break;
}
}
scanf("%d%d", &x, &y);
x--, y--;
while(x != y) {
if(c[x] > c[y]) x = f[x];
else y = f[y];
}
printf("%d\n", x+1);
}
return 0;
}
poj 1330 LCA [ vector 模拟邻接表存图 DFS 找到每个节点的层]
最新推荐文章于 2021-10-03 23:49:47 发布