// verification-helper: PROBLEM https://yukicoder.me/problems/3124 #pragma GCC optimize ("O3") #include using namespace std; #define call_from_test struct Mo{ using F = function; vector ls,rs,ord; int n,width,nl,nr,ptr; F expandL,expandR; F shrinkL,shrinkR; Mo(int n,int width,F expandL,F expandR,F shrinkL,F shrinkR): n(n),width(width),nl(0),nr(0),ptr(0), expandL(expandL),expandR(expandR), shrinkL(shrinkL),shrinkR(shrinkR){} Mo(int n,int width,F expand,F shrink): Mo(n,width,expand,expand,shrink,shrink){} void add(int l,int r){ ls.emplace_back(l); rs.emplace_back(r); } void build(){ ord.resize(ls.size()); iota(ord.begin(),ord.end(),0); sort(ord.begin(),ord.end(), [&](int a,int b){ if(ls[a]/width!=ls[b]/width) return ls[a]ls[idx]) expandL(--nl); while(nrrs[idx]) shrinkR(--nr); return idx; } }; template struct AbsoluteSum{ multiset lp,rp; T sum; AbsoluteSum():sum(0){} T insert(T x){ if(lp.empty()){ lp.emplace(x); rp.emplace(x); return T(0); } auto p=interval(); lp.emplace(x); rp.emplace(x); if(p.first<=x and x<=p.second) return T(0); if(*lp.rbegin()>*rp.begin()){ T a=*lp.rbegin(); T b=*rp.begin(); lp.erase(lp.find(a)); rp.erase(rp.find(b)); rp.emplace(a); lp.emplace(b); } T res=min(abs(p.first-x),abs(p.second-x)); sum+=res; return res; } T erase(T x){ assert(lp.count(x)+rp.count(x)>=2); if(lp.count(x) and rp.count(x)){ lp.erase(lp.find(x)); rp.erase(rp.find(x)); return T(0); } if(lp.count(x)){ lp.erase(lp.find(x)); lp.erase(lp.find(x)); lp.emplace(*rp.begin()); rp.erase(rp.begin()); }else{ rp.erase(rp.find(x)); rp.erase(rp.find(x)); rp.emplace(*lp.rbegin()); lp.erase(--lp.end()); } auto p=interval(); if(p.first<=x and x<=p.second) return T(0); T res=min(abs(p.first-x),abs(p.second-x)); sum-=res; return res; } pair interval(){ assert(!lp.empty()); return make_pair(*lp.rbegin(),*rp.begin()); } T value(){return sum;} }; #undef call_from_test signed main(){ cin.tie(0); ios::sync_with_stdio(0); const char newl = '\n'; int n,q; cin>>n>>q; vector as(n); for(int i=0;i>as[i]; AbsoluteSum dat; auto expand=[&](int i){dat.insert(as[i]);}; auto shrink=[&](int i){dat.erase(as[i]);}; Mo mo(n,400,expand,shrink); for(int i=0;i>l>>r; l--; mo.add(l,r); } mo.build(); vector ans(q); for(int i=0;i