洛谷P1456 Monkey King
#include <iostream>
#include <istream>
#include <sstream>
#include <vector>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <cstring>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <numeric>
#include <chrono>
#include <ctime>
#include <cmath>
#include <cctype>
#include <string>
#include <cstdio>
#include <iomanip>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <iterator>
using namespace std;
//void rfIO()
//{
// FILE *stream1;
// freopen_s(&stream1,"in.txt", "r", stdin);
// freopen_s(&stream1,"out.txt", "w", stdout);
//}
inline int read(int& x) {
char ch = getchar();
int f = 1; x = 0;
while (ch > '9' || ch < '0') {
if (ch == '-')f = -1; ch = getchar(); }
while (ch >= '0' && ch <= '9') {
x = (x << 1) + (x << 3) + ch - '0'; ch = getchar(); }
return x * f;
}
//void ReadFile() {
// FILE* stream1;
// freopen_s(&stream1,"in.txt", "r", stdin);
// freopen_s(&stream1,"out.txt", "w", stdout);
//}
static auto speedup = []() {
ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); return nullptr; }();
const int maxn = 1e5 + 7;
#define ls(x) ltt[x].ls
#define rs(x) ltt[x].rs
#define dis(x) ltt[x].dis
int n,m;
struct Node{
int ls, rs, val, fa,dis;
}ltt[maxn];
int merge(int x, int y){
if (!x || !y) return x + y;
if (ltt[x].val < ltt[y].val)swap(x, y);
rs(x) = merge(rs(x), y);
ltt[rs(x)].fa = x;
if (dis(rs(x)) > dis(ls(x)))swap(ls(x), rs(x));
dis(x) = dis(rs(x)) + 1;
return x;
}
void pop(int x){
ltt[x].val = -1;
ltt[ls(x)].fa = ls(x);
ltt[rs(x)].fa = rs(x);
ltt[x].fa = merge(ls(x), rs(x));
}
int weak(int x){
ltt[x].val >>= 1;
int rt = merge(ls(x), rs(x));
ls(x) = rs(x) = dis(x) = 0;
return ltt[x].fa = ltt[rt].fa = merge(x, rt);
}
int find(int x){
return x == ltt[x].fa ? x : ltt[x].fa = find(ltt[x].fa);
}
void slove(){
for (int i = 1; i <= n; i++){
cin >> ltt[i].val;
ltt[i].fa = i;
ls(i) = 0;
rs(i) = 0;
}
cin >> m;
int a, b;
for (int i = 1; i <= m; i++){
cin >> a >> b;
int fa = find(a), fb = find(b);
if (fa == fb){
cout << -1 << endl;
}
else{
fa = weak(fa);
fb = weak(fb);
int x = merge(fa, fb);
cout << ltt[x].val << endl;
}
}
}
int main()
{
while (cin >> n)slove();
return 0;
}