Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- #define pb push_back
- #define int long long
- #define all(x) (x).begin(), (x).end()
- using namespace std;
- const int N = 5e5 + 5;
- int a[N], n;
- mt19937 gen;
- struct node {
- int key, val, mx, prior;
- node *l, *r;
- node(int k, int v) {
- key = k;
- mx = val = v;
- prior = gen();
- l = r = 0;
- }
- };
- using tnode = node*;
- int mx(tnode t) {
- return (t ? t -> mx : -1);
- }
- void recalc(tnode &t) {
- if (t)
- t -> mx = max({t -> val, mx(t -> l), mx(t -> r)});
- }
- void merge(tnode &t, tnode l, tnode r) {
- if (!l)
- return void(t = r);
- if (!r)
- return void(t = l);
- if (l -> prior > r -> prior)
- merge(l -> r, l -> r, r), t = l;
- else
- merge(r -> l, l, r -> l), t = r;
- recalc(t);
- }
- void split(tnode &t, tnode l, tnode r, int key) { // <=
- if (!t)
- return void(l = r = 0);
- if (t -> key <= key)
- split(t -> r, t -> r, r, key), l = t;
- else
- split(t -> l, l, t -> l, key), r = t;
- recalc(t);
- }
- void add(tnode &t, int s, int x) {
- tnode t1, t2, t3;
- split(t, t1, t3, s);
- t2 = new node(s, x);
- merge(t1, t1, t2);
- merge(t, t1, t3);
- }
- void del(tnode &t, int key) { // del <= key
- cout << "IN" << endl;
- cout << key << ' ' << t << ' ' << mx(t) << ' ' << (t ? t -> key : -1) << endl;
- if (!t)
- return;
- if (t -> key > key)
- del(t -> l, key);
- else {
- cout << "M!" << endl;
- del(t -> r, key);
- cout << "MIDDLE" << endl;
- t = t -> r;
- }
- recalc(t);
- cout << key << ' ' << t << ' ' << mx(t) << endl;
- cout << "OUT" << endl;
- }
- pair<int, int> get(tnode t) {
- if (!t)
- return {-1, -1};
- if (t -> val == t -> mx)
- return {t -> key, t -> val};
- if (t -> mx == mx(t -> l))
- return get(t -> l);
- return get(t -> r);
- }
- signed main() {
- gen.seed(time(0));/*
- ios_base::sync_with_stdio(false);
- cin.tie(nullptr);*/
- cin >> n;
- for (int i = 1; i <= n; i++)
- cin >> a[i];
- sort(a + 1, a + n + 1);
- multiset<pair<int, int> > q;
- //q.insert({a[1] + a[2] + a[3] + a[4] - a[5], a[5]});
- tnode root = 0;
- add(root, a[1] + a[2] + a[3] + a[4] - a[5], a[5]);
- multiset<int> suff;
- for (int i = 7; i <= n; i++)
- suff.insert(a[i]);
- int ans = -1;
- for (int i = 6; i < 7; i++) {
- cout << "FOR" << i << endl;
- del(root, a[i]);
- //cout << 1111 << endl;
- pair<int, int> res = get(root);
- int mx = res.second, sum = res.first + 2 * res.second;
- if (mx != -1) {
- auto it = suff.lower_bound(mx + a[i]);
- if (it == suff.begin())
- continue;
- it--;
- ans = max(ans, sum + a[i] + *it);
- }
- add(root, a[i - 4] + a[i - 3] + a[i - 2] + a[i - 1] - a[i], a[i]);
- suff.erase(suff.find(a[i + 1]));
- }
- cout << ans;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement