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
| #include <iostream> #include <cstring> #include <vector> using namespace std;
const int N = 100010; vector<int>edges[N];
int fa[N], dep[N], son[N], top[N], sz[N]; int n, m;
void dfs(int x, int f, int d){ fa[x] = f, dep[x] = d, sz[x] = 1, son[x] = 0; for(int i=0;i<edges[x].size();i++){ int y = edges[x][i]; if(y==f) continue; dfs(y, x, d+1); sz[x] += sz[y]; if(sz[son[x]] < sz[y]) son[x] = y; } }
void dfs2(int x, int f, int tp){ top[x] = tp; ID[x] = ++tot; if(son[x]) dfs2(son[x], x, tp); for(int i=0;i<edges[x].size();i++){ int y = edges[x][i]; if(y==f || y == son[x]) continue; dfs2(y, x, y); } }
int LCA(int a, int b){ while(top[a]!=top[b]){ if(dep[top[a]] > dep[top[b]]){ a = fa[top[a]]; }else b = fa[top[b]]; } return dep[a] > dep[b] ? b: a; }
int main(){ cin>>n>>m; int a, b; for(int i=1;i<n;i++){ scanf("%d%d", &a, &b); edges[a].push_back(b); edges[b].push_back(a); } dfs(1, 0, 1); dfs2(1,0,1); for(int i=1;i<=n;i++){ printf("%d %d %d\n", i, son[i], top[i]); }
for(int i=1;i<=m;i++){ scanf("%d%d", &a, &b); printf("%d\n", LCA(a, b)); } return 0; }
|