QOJ.ac

QOJ

IDProblemSubmitterResultTimeMemoryLanguageFile sizeSubmit timeJudge time
#19143#1877. Matryoshka DollswyzwyzRE 1ms22168kbC++142.2kb2022-01-28 11:40:372022-05-06 04:19:21

Judging History

你现在查看的是最新测评结果

  • [2023-08-10 23:21:45]
  • System Update: QOJ starts to keep a history of the judgings of all the submissions.
  • [2022-05-06 04:19:21]
  • 评测
  • 测评结果:RE
  • 用时:1ms
  • 内存:22168kb
  • [2022-01-28 11:40:37]
  • 提交

answer

#include<cstdio>
#include<cctype>
#include<set>
#include<cmath>
#include<algorithm>
#include<iostream>

using std::cerr;
using std::endl;

#define maxn 505505

template<class T>

inline T read(){
	T r=0,f=0;
	char c;
	while(!isdigit(c=getchar()))f|=(c=='-');
	while(isdigit(c))r=(r<<1)+(r<<3)+(c^48),c=getchar();
	return f?-r:r;
}

template<class T>

inline T abs(T a){
	return a<0?-a:a;
}

template<class T>

inline T max(T a,T b){
	return a>b?a:b;
}

int n,m,a[maxn],num[maxn],pos[maxn];

struct Q{
	int l,r,num;
	bool operator <(const Q &q) const{
		return pos[l]^pos[q.l]?l<q.l:r>q.r;
	}
}q[maxn];

int id[maxn],lst[maxn],nxt[maxn],pre[maxn],suf[maxn];

long long Sum,sum,ans[maxn];

inline bool cmp(int x,int y){
	return a[x]<a[y];
}

int top,sta[maxn][3];

inline void del(int x){
	int Pre=pre[x],Suf=suf[x];
	if(Pre&&Suf)sum+=abs(Pre-Suf);
	if(Pre)sum-=abs(x-Pre);
	if(Suf)sum-=abs(x-Suf);
	suf[Pre]=Suf,pre[Suf]=Pre;
}

inline void Del(int x){
	int Pre=lst[x],Suf=nxt[x];
	if(Pre&&Suf)Sum+=abs(Pre-Suf);
	if(Pre)Sum-=abs(x-Pre);
	if(Suf)Sum-=abs(x-Suf);
	nxt[Pre]=Suf,lst[Suf]=Pre;
}

int main(){
	n=read<int>();
	m=read<int>();
	for(int i=1;i<=n;i++)
		a[i]=read<int>(),num[a[i]]=i;
	int B=n/sqrt(2*m);
	for(int i=1;i<=n;i++)
		pos[i]=(i-1)/B+1,id[i]=i;
	for(int i=1;i<=m;i++){
		q[i].l=read<int>();
		q[i].r=read<int>();
		q[i].num=i;
	}
	std::sort(q+1,q+1+m);
	std::sort(id+1,id+1+n,cmp);
	for(int i=1;i<=n;i++){
		lst[id[i]]=id[i-1];
		nxt[id[i-1]]=id[i];
		sum+=abs(id[i]-id[i+1]);
	}
	sum-=id[n],Sum=sum;
	for(int i=1,j=1;j<=pos[n];j++){
		if(pos[q[i].l]==j){
			sum=Sum;
			int L=(j-1)*B+1,l=L,r=n;
			for(int k=l;k<=n;k++)
				pre[k]=lst[k],suf[k]=nxt[k];
			for(;pos[q[i].l]==j;i++){
				while(r>q[i].r)del(r--);
				long long lstsum=sum;
				top=0;
				while(l<q[i].l){
					top++,sta[top][1]=l;
					sta[top][0]=pre[l];
					sta[top][2]=suf[l];
					del(l++);
				}
				ans[q[i].num]=sum;
				sum=lstsum,l=L;
				while(top){
					int Pre=sta[top][0];
					int x=sta[top][1];
					int Suf=sta[top][2];
					suf[Pre]=x,pre[Suf]=x;
					top--;
				}
			}
		}
		for(int k=(j-1)*B+1;k<=j*B;k++)Del(k);
	}
	for(int i=1;i<=m;i++)
		printf("%lld\n",ans[i]);
	return 0;
}

Details

Tip: Click on the bar to expand more detailed information

Test #1:

score: 100
Accepted
time: 1ms
memory: 22168kb

input:

5 5
1 5 2 4 3
1 5
1 4
1 3
1 2
1 1

output:

7
5
3
1
0

result:

ok 5 number(s): "7 5 3 1 0"

Test #2:

score: -100
Runtime Error

input:

1 1
1
1 1

output:


result: