#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <cmath> #include <string> #define Rep(i, x, y) for (int i = x; i <= y; i ++) #define RepE(i, x) for (int i = pos[x]; i; i = g[i].nex) #define Dwn(i, x, y) for (int i = x; i >= y; i --) #define u t[x] #define r t[y] #define lc u.ch[0] #define rc u.ch[1] #define Rc t[rc] #define Lc t[lc] using namespace std; typedef long long LL; const int N = 100005; struct arr { int ch[2], vl, d; } t[N]; int n, par[N], a[N], m; int Fd(int x) { return (par[x] == x) ? x : (par[x] = Fd(par[x])); } int Merge(int x, int y) { if (!x || !y) return max(x, y); if (u.vl < r.vl) swap(x, y); rc = Merge(rc, y); par[rc] = x; if (Rc.d > Lc.d) swap(rc, lc); (!rc) ? u.d = 0 : u.d = Rc.d + 1; return x; } int Del(int x) { par[lc] = lc, par[rc] = rc; int y = Merge(lc, rc); u.d = lc = rc = 0; return y; } void Solve(int x, int y) { int l1, r1; u.vl /= 2, r.vl /= 2; l1 = Del(x), r1 = Del(y); l1 = Merge(l1, x); r1 = Merge(r1, y); x = Merge(l1, r1); printf("%d\n", u.vl); } int main() { while (~scanf ("%d", &n)) { Rep(x, 1, n) scanf ("%d", &a[x]), u.vl = a[x], par[x] = x, lc = rc = u.d = 0; scanf ("%d", &m); int x, y; Rep(i, 1, m) { scanf ("%d%d", &x, &y); x = Fd(x), y = Fd(y); if (x == y) { puts("-1"); continue ; } Solve(x, y); } } return 0; }
左偏树 hdu1512
最新推荐文章于 2020-09-02 11:16:31 发布