Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- #include <ext/pb_ds/assoc_container.hpp>
- #include <ext/pb_ds/tree_policy.hpp>
- using namespace std;
- using namespace __gnu_pbds;
- #define debug(x) cerr << '[' << (#x) << "] = " << x << '\n';
- template<class T> using ordered_set = tree<T, null_type , less<T> , rb_tree_tag , tree_order_statistics_node_update> ;
- const int maxn = 1005;
- vector<int>g[maxn];
- void PlayGround() {
- int N; cin >> N;
- for(int i=1; i<=N; ++i) {
- int m; cin >> m;
- while(m--) {
- int child; cin >> child;
- g[i].push_back(child);
- g[child].push_back(i);
- }
- }
- int l = 15;
- vector<vector<int>>up(N+5, vector<int>(l+1));
- vector<int>tin(N+5), tout(N+5);
- int timer = 0;
- function<void(int,int)> dfs = [&] (int node, int parent) {
- tin[node] = timer++;
- up[node][0] = parent;
- for(int i=1; i<=l; ++i)
- up[node][i] = up[up[node][i-1]][i-1];
- for(int child : g[node]) if(child != parent) {
- dfs(child, node);
- }
- tout[node] = timer++;
- };
- dfs(1, 1);
- auto isAncestor = [=] (int u, int v) {
- return tin[u] <= tin[v] && tout[u] >= tout[v];
- };
- auto getLCA = [=] (int u, int v) {
- if(isAncestor(u, v)) return u;
- if(isAncestor(v, u)) return v;
- for(int i=l; i>=0; --i) if(!isAncestor(up[u][i], v)) {
- u = up[u][i];
- }
- return up[u][0];
- };
- int q; cin >> q;
- while(q--) {
- int u, v; cin >> u >> v;
- cout << getLCA(u, v) << '\n';
- }
- for(int i=1; i<=N; ++i)
- g[i].clear();
- #ifndef ONLINE_JUDGE
- cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
- #endif
- }
- int main() {
- ios_base::sync_with_stdio(0);
- cin.tie(0);
- cout.tie(0);
- #ifndef ONLINE_JUDGE
- freopen("input.txt", "r", stdin);
- #endif
- int t; cin >> t;
- for(int i=1; i<=t; ++i) {
- cout << "Case " << i << ":\n";
- PlayGround();
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement