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>
#define C first
#define V second
using namespace std;
typedef pair<long long, long long> ii;
int n, m;
long long op[300005];
ii arr[200005];
struct maxM{
multiset<long long> take;
multiset<long long> notake;
long long total = 0;
int l = -1, r = -1;
void include(long long pos){
long long x = arr[pos].V;
if(l == -1){
l = pos; r = pos;
}
else{
r++;
}
//cout << "INC: " << x << endl;
take.insert(x); total += x;
if((int) take.size() > m){
auto it = take.begin();
total -= *it;
take.erase(it);
notake.insert(*it);
}
}
void exclude(){
long long x = arr[l].V;
l++;
//cout << "EXC: " << x << endl;
auto it = notake.find(x);
if(it != notake.end()){
notake.erase(it);
return;
}
take.erase(take.find(x)); total -= x;
while((int) take.size() < m && !notake.empty()){
auto it2 = (--notake.end());
take.insert(*it2);
total += *it2;
notake.erase(it2);
}
}
long long get(){
if((int) take.size() == m) return total;
else return -1e18;
}
void reset(){
//cout << "RESET: " << endl;
take.clear();
notake.clear();
l = -1, r = -1;
total = 0;
}
};
maxM S;
signed main(){
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
cin >> n >> m; m -= 2;
for(int i = 1;i <= n;i++) cin >> arr[i].V >> arr[i].C;
sort(arr+1,arr+n+1);
long long ans = -1e18;
fill(op,op+300004, n); op[0] = 1;
for(int bit = (1<<17);bit >= 1;bit >>= 1){
S.reset();
for(int s = bit;s < n - m;s += 2*bit){
int L, R;
L = op[s-bit];
R = op[s+bit];
L = max(s+1, L);
long long bestValue = -1e18;
long long bestPos = -1;
for(int e = L;e <= R;e++){
long long val = S.get() + arr[s].V + arr[e].V - 2*arr[e].C + 2*arr[s].C;
ans = max(ans, val);
if(bestValue < val){
bestValue = val;
bestPos = e;
}
if(e != R){
//cout << "INC: " << e << endl;
S.include(e);
}
}
while(S.l <= s + 2*bit && S.l <= S.r){
//if(s == 24) cout << "YUDODIS" << endl;
//cout << "EXC: " << S.l << endl;
S.exclude();
}
//cout << s << " " << L << " " << R << " " << bestValue << " " << bestPos << endl;
op[s] = bestPos;
}
}
cout << 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... |