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 clear(X) decltype(X)().swap(X);
using namespace std;
using ll=long long;
struct pii {
int l, r;
bool operator<(pii b) const { return l+r<b.l+b.r; }
};
int main() {
ios::sync_with_stdio(0);cin.tie(0);
int K, N, M=0;
cin>>K>>N;
pii A[N];
ll s=0;
for(int i=0; i<N; i++) {
char a, b;
int l, r;
cin>>a>>l>>b>>r;
if(l>r) swap(l, r);
if(a!=b) A[M++]={l, r};
else s+=r-l;
}
N=M;
s+=N;
if(K==1) {
int *B=(int*)&A;
nth_element(B, B+N, B+N*2);
int m=B[N];
for(int i=0; i<2*N; i++) s+=abs(B[i]-m);
cout<<s<<'\n';
return 0;
}
sort(A, A+N);
ll B[N], w=0;
priority_queue<int> L;
priority_queue<int, vector<int>, greater<int>> R;
auto balance=[&] {
if(L.size()>R.size()) {
int v=L.top();
L.pop(), R.push(v);
w+=v*2;
} else if(L.top()>R.top()) {
int l=L.top(), r=R.top();
L.pop(), L.push(r);
R.pop(), R.push(l);
w+=(l-r)*2;
}
};
for(int i=0; i<N; i++) {
auto[l,r]=A[i];
L.push(l), w-=l;
balance();
L.push(r), w-=r;
balance();
B[i]=w-(L.size()<R.size() ? R.top() : 0);
}
w=0;
clear(L);
clear(R);
ll t=B[N-1];
for(int i=N; --i;) {
auto[l,r]=A[i];
L.push(l), w-=l;
balance();
L.push(r), w-=r;
balance();
t=min(t, w-(L.size()<R.size() ? R.top() : 0)+B[i-1]);
}
cout<<s+t<<'\n';
}
# | 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... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |