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;
using ll=long long;
using PQ=priority_queue<int>;
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 B[N], s=0, w=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;
}
s+=N=M;
sort(A, A+N);
PQ L, R;
auto add=[&](pii v) {
L.push(v.l), R.push(-v.r);
w+=v.r-v.l;
if(L.top()>-R.top()) {
int l=L.top(), r=-R.top();
L.pop(), R.pop();
L.push(r), R.push(-l);
w+=(l-r)*2;
}
return w;
};
for(int i=0; i<N; i++) B[i]=add(A[i]);
w=0;
PQ().swap(L);
PQ().swap(R);
ll t=N ? B[N-1] : 0;
if(N && K==2) for(int i=N; --i;) t=min(t, add(A[i])+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... |