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
#define sz(x) (int)x.size()
#define ff first
#define ss second
const int N = 300005;
const int M = 1e9 + 7;
int T, n, k, s1[N], s2[N];
char c1[N], c2[N];
signed main(){
ios::sync_with_stdio(false); cin.tie(0);
cin >> k >> n;
for(int i = 1; i <= n; i++){
cin >> c1[i] >> s1[i] >> c2[i] >> s2[i];
}
int ans = 0;
if(k == 1){
vector <int> v;
for(int i = 1; i <= n; i++){
if(c1[i] == c2[i]){
ans += abs(s1[i]-s2[i]);
}
else {
v.push_back(s1[i]);
v.push_back(s2[i]);
}
}
sort(v.begin(), v.end());
int x = (sz(v)+1)/2;
x--;
if(x >= 0) x = v[x];
for(auto i : v){
ans += abs(i-x);
}
cout << ans+sz(v)/2 << "\n";
return 0;
}
vector <pair<int,pair<int,int>>> v1;
for(int i = 1; i <= n; i++){
if(c1[i] != c2[i]){
v1.push_back({(s1[i]+s2[i])/2,{min(s1[i],s2[i]),max(s1[i],s2[i])}});
}
else {
ans += abs(s1[i]-s2[i]);
}
}
ans += sz(v1);
if(sz(v1) > 0){
sort(v1.begin(), v1.end());
}
multiset <int> st1, st2;
vector <int> p(sz(v1),0), f(sz(v1),0);
int sm1 = 0, sm2 = 0;
for(int j = 0; j < sz(v1); j++){
pair <int,pair<int,int>> i = v1[j];
st1.insert(i.ss.ff);
st1.insert(i.ss.ss);
sm1 += (i.ss.ff);
sm1 += (i.ss.ss);
st2.insert(*st1.rbegin());
sm2 += *st1.rbegin();
sm1 -= *(--st1.end());
st1.erase(--st1.end());
sm2 += *st1.rbegin();
st2.insert(*st1.rbegin());
sm1 -= *(--st1.end());
st1.erase(--st1.end());
sm1 += *st2.begin();
st1.insert(*st2.begin());
sm2 -= *(st2.begin());
st2.erase(st2.begin());
int med = (*st1.rbegin());
p[j] = (sz(st1)*med - sm1);
p[j] += (sm2 - med*sz(st2));
}
st1.clear();
st2.clear();
sm1 = sm2 = 0;
for(int j = sz(v1)-1; j >= 0; j--){
pair <int,pair<int,int>> i = v1[j];
st1.insert(i.ss.ff);
st1.insert(i.ss.ss);
sm1 += (i.ss.ff);
sm1 += (i.ss.ss);
st2.insert(*st1.rbegin());
sm2 += *st1.rbegin();
sm1 -= *(--st1.end());
st1.erase(--st1.end());
sm2 += *st1.rbegin();
st2.insert(*st1.rbegin());
sm1 -= *(--st1.end());
st1.erase(--st1.end());
sm1 += *st2.begin();
st1.insert(*st2.begin());
sm2 -= *(st2.begin());
st2.erase(st2.begin());
int med = (*st1.rbegin());
f[j] = (sz(st1)*med - sm1);
f[j] += (sm2 - med*sz(st2));
}
int mn = 0;
if(sz(v1) > 0) mn = min(p[sz(v1)-1],f[0]);
for(int i = 0; i < sz(v1)-1; i++){
mn = min(mn,p[i]+f[i+1]);
}
cout << ans + mn << "\n";
return 0;
}
# | 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... |