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;
int n, k;
long long sameside=0;
vector<pair<int, int>>diff;
bool comp(pair<int, int>a, pair<int, int>b){
return (a.first+a.second<b.first+b.second);
}
long long pre[100005];
multiset<int>low;
multiset<int>up;
long long lowsum=0;
long long upsum=0;
long long res=0;
void add(int x){
if (low.size()==0){
low.insert(x);
lowsum+=x;
return;
}
if (x<=*(--low.end())){
low.insert(x);
lowsum+=x;
}else{
up.insert(x);
upsum+=x;
}
}
long long ans=2e18;
void rebalance(){
while (up.size()>low.size()){
low.insert(*(up.begin()));
lowsum+=*(up.begin());
upsum-=*(up.begin());
up.erase(up.begin());
}
while (low.size()>up.size()+1){
up.insert(*(--low.end()));
upsum+=*(--low.end());
lowsum-=*(--low.end());
low.erase(--low.end());
}
}
void INSERT(int val){
add(val);
rebalance();
}
int main(){
cin>>k>>n;
for (int i=1;i <=n; i++){
char a, b;
int x, y;
cin>>a>>x>>b>>y;
if (a==b){
sameside+=abs(x-y);
}else{
diff.push_back({x, y});
}
}
// diff={{1, 1}, {2, 2}, {3, 4}, {5, 8}};
int n_=diff.size();
sameside+=n_;
sort(diff.begin(), diff.end(), comp);
for (int i=0; i<diff.size(); i++){
INSERT(diff[i].first);
INSERT(diff[i].second);
pre[i]=*(--low.end())*((int)low.size())-lowsum+upsum-(*(--low.end())*((int)up.size()));
//cout<<i<<" "<<pre[i]<<'\n';
}
ans=pre[n_-1];
if (k==2){
low.clear();
up.clear();
lowsum=upsum=0;
for (int i=n_-1; i>=0; i--){
INSERT(diff[i].first);
INSERT(diff[i].second);
ans=min(ans, *(--low.end())*((int)low.size())-lowsum+upsum-(*(--low.end())*((int)up.size())) + pre[i-1]);
}
cout<<ans+sameside;
}else
cout<<pre[n_-1]+sameside;
}
Compilation message (stderr)
bridge.cpp: In function 'int main()':
bridge.cpp:68:20: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<std::pair<int, int> >::size_type' {aka 'long unsigned int'} [-Wsign-compare]
68 | for (int i=0; i<diff.size(); i++){
| ~^~~~~~~~~~~~
# | 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... |