This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
set<pair<int, int>> chosen;
set<pair<int, int>, greater<>> have;
long long curSum = 0;
int lt = 1;
int rt = 0;
int n, d, start;
int du;
int arr[100001];
long long ans = -1e18;
void giveToHave()
{
du++;
have.insert(*chosen.begin());
curSum -= chosen.begin()->first;
chosen.erase(chosen.begin());
}
void giveToChosen()
{
du--;
chosen.insert(*have.begin());
curSum += have.begin()->first;
have.erase(have.begin());
}
void Add(int x)
{
have.insert(make_pair(arr[x], x));
}
void Del(int x)
{
if (chosen.find(make_pair(arr[x], x)) != chosen.end())
{
chosen.erase(make_pair(arr[x], x));
curSum -= arr[x];
du++;
}
else have.erase(make_pair(arr[x], x));
}
int calcDis(int l, int r)
{
if (l > r) return 0;
if (start <= l) return(l - start + (r - l));
if (start >= r) return(start - r + (r - l));
return (min(start - l, r - start) + (r - l));
}
void stable()
{
while (du < 0 && !chosen.empty()) giveToHave();
while ((du > 0 && !have.empty())) giveToChosen();
while (!have.empty() && !chosen.empty() && have.begin()->first > chosen.begin()->first) giveToHave(), giveToChosen();
}
long long cost(int l, int r)
{
while (lt != l || rt != r)
{
while (rt < r)
{
du += calcDis(lt, rt) - calcDis(lt, rt + 1);
rt++;
Add(rt);
stable();
}
while (rt > lt && rt > r)
{
du += calcDis(lt, rt) - calcDis(lt, rt - 1);
Del(rt);
rt--;
stable();
}
while (lt < rt && lt < l)
{
du += calcDis(lt, rt) - calcDis(lt + 1, rt);
Del(lt);
lt++;
stable();
}
while (lt > l)
{
du += calcDis(lt, rt) - calcDis(lt - 1, rt);
lt--;
Add(lt);
stable();
}
}
return curSum;
}
void divide(int l, int r, int gL, int gR)
{
if (l > r) return;
int mid = (l + r) / 2;
long long bestCost = -1e18;
int bestPos = gL;
for (int i = gL; i <= min(mid, gR); i++)
{
if (cost(i, mid) > bestCost)
{
bestCost = cost(i, mid);
bestPos = i;
}
}
ans = max(ans, bestCost);
divide(l, mid - 1, gL, bestPos);
divide(mid + 1, r, bestPos, gR);
}
long long findMaxAttraction(int _n, int _start, int _d, int *attraction)
{
n = _n;
d = _d;
start = _start + 1;
for (int i = 1; i <= n; i++) arr[i] = attraction[i - 1];
du = d;
divide(1, n, 1, n);
return ans;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |