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;
#define int long long
int n, m, v[1000005], c[1000005], ans = 0;
pair<int, int> dp[1000005];
struct num{
int V, C;
num();
num(int A, int B){
V = A, C = B;
}
};
bool operator < (num a, num b){
return a.C < b.C;
}
vector<num> vec;
deque<num> dq;
multiset<int> ms;
void solve(){
sort(vec.begin(), vec.end());
for(auto i: vec){
ans += i.V;
ms.insert(i.V);
dq.push_back(i);
}
ans -= 2ll * (vec.back().C - vec[0].C);
int p = n;
while(p > m){
while(ms.find(dq.front().V) == ms.end()) dq.pop_front();
while(ms.find(dq.back().V) == ms.end()) dq.pop_back();
num fr = dq.front(), ba = dq.back();
dq.pop_front();
while(ms.find(dq.front().V) == ms.end()) dq.pop_front();
int if1 = -fr.V + abs(fr.C - dq.front().C) + abs(fr.C - dq.back().C) - abs(dq.back().C - dq.front().C);
dq.push_front(fr);
dq.pop_back();
while(ms.find(dq.back().V) == ms.end()) dq.pop_back();
int if2 = -ba.V + abs(ba.C - dq.back().C) + abs(ba.C - dq.front().C) - abs(dq.back().C - dq.front().C);;
dq.push_back(ba);
if(max(if1, if2) >= 0){
if(if1 > if2){
dq.pop_front();
ms.erase(ms.find(fr.V));
}
else{
dq.pop_back();
ms.erase(ms.find(ba.V));
}
ans += max(if1, if2);
}
else{
int s = max(if1, if2);
int x = 0;
for(auto i: ms){
if(i != fr.V && i != ba.V){
x = i; break;
}
}
if(x <= abs(s)){
ans -= x;
ms.erase(ms.find(x));
}
else{
ans += s;
if(if1 > if2){
dq.pop_front();
ms.erase(ms.find(fr.V));
}
else{
dq.pop_back();
ms.erase(ms.find(ba.V));
}
}
}
p--;
}
cout << ans;
}
signed main(){
if (ifstream("text.txt"))
{
freopen("text.txt", "r", stdin);
#ifdef CHECKING
freopen(taskname".out", "w", stdout);
#else
//\freopen("text.out", "w", stdout);
#endif //CHECKING
}
//freopen("a.inp", "r", stdin);
//freopen("a.out", "w", stdout);
ios_base::sync_with_stdio(NULL); cin.tie(nullptr); cout.tie(nullptr);
cin >> n >> m;
for(int i = 1; i <= n; i++){
cin >> v[i] >> c[i];
vec.push_back(num(v[i], c[i]));
}
solve();
}
Compilation message (stderr)
cake3.cpp: In function 'int main()':
cake3.cpp:88:16: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)' declared with attribute 'warn_unused_result' [-Wunused-result]
88 | freopen("text.txt", "r", stdin);
| ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |