求助卡常
查看原帖
求助卡常
366639
hh弟中弟楼主2025/1/18 21:33
#include<bits/stdc++.h>
#define fi first
#define se second
#define pii std::pair<int,int>
#define eb emplace_back
#define pb push_back
typedef long long ll;
typedef unsigned long long ull;
inline int read(){char ch=getchar_unlocked();ll x=0,f=1;for(;ch<'0'||ch>'9';ch=getchar_unlocked())if(ch=='-')f=-1;for(;ch>='0'&&ch<='9';ch=getchar_unlocked())x=(x<<3)+(x<<1)+(ch^48);return x*f;}
template<typename T> inline void write(T x){if(x>=10)write(x/10);putchar(x%10+'0');}
template<typename T> inline void Min(T&x,T y){if(x>y)x=y;}
template<typename T> inline void Max(T&x,T y){if(x<y)x=y;}
inline int ABS(int x){return x<0?-x:x;}
const int N=5e5+5;
int n,m,id[N],c[N],top,p[N],len,a[N],now,ql[N];
ll res,ans[N],pre[N],suf[N];
struct QU{int l,r,id;}q[N];
struct STA{ll *x,y;}s[N];
inline void modi(ll &x,ll y,bool pd){if(x==y)return;if(pd)s[++top]={&x,x};x=y;}
inline void back(int x){while(top>x)*s[top].x=s[top].y,--top;}
inline void del(int x,bool pd){
	int zcres=0;
	if(pre[x]==suf[x])return;
	if(pre[x]==x){
		zcres-=ABS(p[x]-p[suf[x]]);modi(res,res+zcres,pd);
		modi(pre[suf[x]],suf[x],pd);return;
	}
	if(suf[x]==x){
		zcres-=ABS(p[x]-p[pre[x]]);modi(res,res+zcres,pd);
		modi(suf[pre[x]],pre[x],pd);return;
	}
	zcres+=-ABS(p[x]-p[pre[x]])-ABS(p[x]-p[suf[x]])+ABS(p[pre[x]]-p[suf[x]]);
	modi(res,res+zcres,pd);modi(pre[suf[x]],pre[x],pd);modi(suf[pre[x]],suf[x],pd);
}
signed main(){
    // freopen("in.in","r",stdin);freopen("out.out","w",stdout);
    std::ios::sync_with_stdio(false);std::cin.tie(0);std::cout.tie(0);
    n=read();m=read();len=n/std::sqrt(m);for(int i=1;i<=n;++i)id[i]=(i-1)/len+1,a[i]=read(),p[a[i]]=i;
    for(int i=1;i<=m;++i)q[i].l=read(),q[i].r=read(),q[i].id=i;std::sort(q+1,q+m+1,[](QU&A,QU&B){
    	return id[A.l]==id[B.l]?A.r>B.r:id[A.l]<id[B.l];
    });
    for(int i=1;i<=m;++i)Max(ql[id[q[i].l]],q[i].r);
    int la=0,l=1,r=0;
    for(int i=1;i<=m;++i){
    	int L=q[i].l,R=q[i].r;
    	if(L==R){ans[q[i].id]=0;continue;}
    	if(id[L]==id[R]){
    		ll &res=ans[q[i].id];
    		now++;int mi=n,mx=0;
    		for(int i=L;i<=R;++i)Min(mi,a[i]),Max(mx,a[i]),c[a[i]]=now;
    		for(int i=mi+1,la=mi;i<=mx;++i)if(c[i]==now){res+=ABS(p[i]-p[la]),la=i;}
    		continue;
    	}
    	if(id[L]!=la){
    		res=0;now++;top=0;int mi=n,mx=0;l=id[L]*len-len+1,r=ql[id[L]];
    		for(int i=l;i<=r;++i)c[a[i]]=now,Max(mx,a[i]),Min(mi,a[i]);
    		pre[mi]=mi,suf[mx]=mx;
    		for(int i=mi+1,la=mi;i<=mx;++i)if(c[i]==now)res+=ABS(p[i]-p[la]),suf[la]=i,pre[i]=la,la=i;
    		la=id[L];
    	}
    	while(r>R)del(a[r--],0);while(l<L)del(a[l++],1);
    	ans[q[i].id]=res;l=id[L]*len-len+1;back(0);
    }
    for(int i=1;i<=m;++i)write(ans[i]),putchar('\n');
}

调块长,改 int,按左端点块排序都试过了,第十七个点一直都是 5.20s,动都不动。

2025/1/18 21:33
加载中...