跳到正文

剪贴板

剪贴板 1869nobo

原文
剪贴板信息

剪贴板信息

收录
更新
  • 100100 分,是否能够过要卡评测波动。
C++
#include<cmath>
#include<fstream>
#include<algorithm>
#define clz(x) __builtin_clzll(x)
#define ctz(x) __builtin_ctzll(x)
#define u64 unsigned long long
const int N=550000;
using namespace std;
int n,B,L,nd,m,l,r,a[N],id[N];
long long res,ans[N];
u64 *o[5],buf[N<<2];
struct que
{
	int l,r,id;
	bool operator < (const que &b) const
	{
		return l/B==b.l/B?((l/B&1)?b.r<r:r<b.r):l<b.l;
	}
}q[N];
u64 *ask(int n)
{
	static u64 *bt=buf+(N<<2);
	return bt-=n;
}
void work(int n)
{
	L=log(n)/log(64);
	for(int z=1;z<=L+1;++z)
		o[z-1]=ask((n+(1<<6*z)-1)>>6*z);
}
void insert(int x)
{
	for(int z=0;z<=L;++z)
	{
		u64 p=1ull<<(x&63);
		if(o[z][x>>6]&p)return;
		o[z][x>>6]|=p;
		x>>=6;
	}
}
void erase(int x)
{
	for(int z=0;z<=L;++z)
	{
		u64 p=1ull<<(x&63);
		if(o[z][x>>6]&=~p)return;
		x>>=6;
	}
}
int pre(int x)
{
	for(int z=0;z<=L;++z)
	{
		int y=x>>6*z;
		u64 p=o[z][y>>6]&((1ull<<(y&63))-1);
		if(p)
		{
			int res=x>>(z+1)*6<<(z+1)*6;
			res|=(63-clz(p))<<z*6;
			for(int w=z-1;~w;--w)
				res|=(63-clz(o[w][res>>(w+1)*6]))<<w*6;
			return res;
		}
	}
	return 0;
}
int suf(int x)
{
	for(int z=0;z<=L;++z)
	{
		int y=x>>6*z;
		u64 p=o[z][y>>6]>>(y&63);
		if(p>1)
		{
			int res=y>>6<<(z+1)*6;
			res|=(ctz(p>>1)+(y&63)+1)<<z*6;
			for(int w=z-1;~w;--w)
				res|=ctz(o[w][res>>(w+1)*6])<<w*6;
			return res;
		}
	}
	return 0;
}
void add(int x)
{
	int pe=pre(a[x]),sf=suf(a[x]);
	if(pe>0&&sf<=n)res-=abs(id[pe]-id[sf]);
	if(pe>0)res+=abs(id[pe]-x);
	if(sf<=n)res+=abs(x-id[sf]);
	insert(a[x]);
}
void del(int x)
{
	erase(a[x]);
	int pe=pre(a[x]),sf=suf(a[x]);
	if(pe>0&&sf<=n)res+=abs(id[pe]-id[sf]);
	if(pe>0)res-=abs(id[pe]-x);
	if(sf<=n)res-=abs(x-id[sf]);
}
int main()
{
	scanf("%d%d",&n,&m);
	B=n/sqrt((m+1)/2);work(n+1);
	for(int i=1;i<=n;++i)
	{
		scanf("%d",&a[i]);
		id[a[i]]=i;
	}
	insert(0),insert(n+1);
	for(int i=0;i<m;++i)
		scanf("%d%d",&q[i].l,&q[i].r),q[i].id=i;
	sort(q,q+m);l=1,r=0;
	for(int i=0;i<m;++i)
	{
		while(q[i].l<l)add(--l);
		while(r<q[i].r)add(++r);
		while(q[i].r<r)del(r--);
		while(l<q[i].l)del(l++);
		ans[q[i].id]=res;
	}
	for(int i=0;i<m;++i)printf("%lld\n",ans[i]);
	return 0;
}