#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#define fst first
#define snd second
#define pb push_back
#define ALL(x) x.begin(),x.end()
#define SZ(x) (int)x.size()
#define forn(i,a,b) for(int i = a; i< b; i++)
using namespace std;
using namespace __gnu_pbds;
typedef long long ll;
template<typename T>
using imset = tree<T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update>;
vector<ll> laderach(vector<pair<ll,ll>> rng){
imset<pair<ll,ll>> left;
imset<pair<ll,ll>> right;
set<ll> vals; vals.insert(-1);
auto it = vals.begin();
ll aux = 0;
vector<ll> ltr(SZ(rng),0);
ll resaux=0;
forn(i,0,SZ(rng)){
left.insert({rng[i].fst,aux}); aux++;
right.insert({rng[i].snd,aux}); aux++;
vals.insert(rng[i].fst);
vals.insert(rng[i].snd);
resaux+=max((ll)0,(rng[i].fst-(*it))*2);
//while(true){
ll cleft=0;
auto lait = left.lower_bound({*it+1,-1});
if(lait!=left.end()){
cleft=SZ(left)-left.order_of_key(*lait);
}
ll cright=SZ(right);
auto rait = right.upper_bound({*it,1000000000000000});
if(rait!=right.end()){
cright=right.order_of_key(*rait);
}
if(cleft>cright){
ll last=*it; it++;
ll neww = *it;
resaux+=(neww-last)*2*cright;
resaux-=(neww-last)*2*cleft;
}
ltr[i]=resaux;
//cout<<resaux<<" "<<i<<'\n';
}
return ltr;
}
int main(){
ll k,n; cin>>k>>n;
vector<pair<ll,ll>> rng;
ll resbase = 0;
forn(i,0,n){
char a,b;
ll l; ll r;
cin>>a>>l>>b>>r;
if(l>r) swap(l,r);
if(a!=b){
rng.pb({l,r});
resbase++;
}
resbase+=r-l;
}
sort(ALL(rng));
//cout<<resbase<<'\n';\
vector<ll> resltr = laderach(rng);
forn(i,0,SZ(rng)){
rng[i].fst-=1000000000;
rng[i].snd-=1000000000;
rng[i].fst*=-1;
rng[i].snd*=-1;
swap(rng[i].fst,rng[i].snd);
}
reverse(ALL(rng));
vector<ll> resrtl = laderach(rng);
/* forn(i,0,SZ(rng)) cout<<resrtl[i]<<" "<<resltr[i]<<'\n';
cout<<(SZ(rng)>0?resltr[SZ(rng)-1]:0)+resbase<<'\n';*/
ll mini = (SZ(rng)>0?resrtl[SZ(rng)-1]:0);
if(k==2){
forn(i,0,SZ(rng)){
//cout<<0<<" "<<i<<" -> "<<resrtl[i]+(SZ(rng)-(i+1)>0?resltr[SZ(rng)-(i+1)]:0)<<'\n';
mini=min(mini,resrtl[i]+(SZ(rng)-(i+1)>0?resltr[SZ(rng)-(i+1)]:0));
}
}
cout<<mini+resbase<<'\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... |