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;
typedef long long ll;
typedef pair<int,int> pii;
const int mx=300000,MID=150000,sq=1350;
struct NN {
ll sum,sl,sr,cnt;
} s[1<<21];
NN merge(NN a, NN b) {
NN res;
res.sum=a.sum+b.sum;
res.cnt=a.cnt+b.cnt;
res.sl=a.sl+a.cnt*b.sum+b.sl;
res.sr=b.sr+b.cnt*a.sum+a.sr;
return res;
}
ll fast2_query(int l, int r, int idx, int x, int val) {
if (x>r) return s[idx].sr+s[idx].sum*(ll)(x-r);
if (x<l) return s[idx].sl+s[idx].sum*(ll)(l-x);
if (l==r) {
s[idx]={val,val,val,1};
return val;
}
int mid=(l+r)/2;
ll res1=fast2_query(l,mid,2*idx,x,val);
ll res2=fast2_query(mid+1,r,2*idx+1,x,val);
s[idx]=merge(s[2*idx],s[2*idx+1]);
return res1+res2;
}
int have[mx+5],idx_seq=-1;
vector<int> seq;
deque<int> dq[mx+5];
ll ans=0;
void add(int val) {
if (!have[val]) {
int pos=seq[++idx_seq];
dq[1].push_back(pos);
ans+=fast2_query(1,mx,1,pos,1);
} else {
int max_pos=dq[have[val]].front();
dq[have[val]].pop_front();
dq[have[val]+1].push_back(max_pos);
ans+=fast2_query(1,mx,1,max_pos,have[val]+1);
}
++have[val];
}
void del(int val) {
int min_pos=dq[have[val]].back();
dq[have[val]].pop_back();
if (have[val]==1) --idx_seq;
else dq[have[val]-1].push_front(min_pos);
--have[val];
ans-=(fast2_query(1,mx,1,min_pos,have[val])+1);
}
int n,q,a[mx+5];
struct Query {
int l,r,idx;
bool operator<(Query other) const {
return pii(l/sq,((l/sq)&1) ? -r : +r)<pii(other.l/sq,((other.l/sq)&1) ? -other.r : +other.r);
}
};
vector<Query> ques;
ll Ans[50005];
int main() {
ios_base::sync_with_stdio(0); cin.tie(0);
int ll=MID,rr=MID;
seq.push_back(MID);
for (int i=1; i<mx; ++i) {
if (i%2==0) seq.push_back(--ll);
else seq.push_back(++rr);
}
cin>>n>>q;
for (int i=0; i<n; ++i) cin>>a[i];
for (int i=0; i<q; ++i) {
int l,r; cin>>l>>r;
ques.push_back({--l,--r,i});
}
sort(ques.begin(),ques.end());
int cur_l=0;
int cur_r=-1;
for (auto q : ques) {
if (q.l>cur_r) {
for (int i=q.l; i<=q.r; ++i) add(a[i]);
for (int i=cur_l; i<=cur_r; ++i) del(a[i]);
cur_l=q.l; cur_r=q.r;
} else if (q.r<cur_l) {
for (int i=q.l; i<=q.r; ++i) add(a[i]);
for (int i=cur_l; i<=cur_r; ++i) del(a[i]);
cur_l=q.l; cur_r=q.r;
} else {
while (cur_l>q.l) add(a[--cur_l]);
while (cur_r<q.r) add(a[++cur_r]);
while (cur_l<q.l) del(a[cur_l++]);
while (cur_r>q.r) del(a[cur_r--]);
}
Ans[q.idx]=ans;
}
for (int i=0; i<q; ++i) cout<<Ans[i]<<"\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... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |