P2709 小B的询问 ( 莫队 )

题目描述:点击进入

在这里插入图片描述

思路

莫队经典例题
保存个模板吧
哦,对了,每日一错:定义的 int 不要输入 lld 要不 WA 到你怀疑人生/(ㄒoㄒ)/~~
(顺便说一句,莫队卡常 + O2 真快)
如图
正常版
在这里插入图片描述
卡常 + O2
在这里插入图片描述

代码1(正常)
//#pragma GCC optimize(2) 
//#pragma GCC optimize(3) 
#include<cstdio>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxn=1e5+10;
int n,m,k,block,cnt,sum[maxn],a[maxn],ans[maxn];
struct node
{
	int l;
	int r;
	int id;
	int bl;
}p[maxn];
void add(int x)
{
	cnt-=sum[a[x]]*sum[a[x]];
	sum[a[x]]++;
	cnt+=sum[a[x]]*sum[a[x]];
}
void del(int x)
{
	cnt-=sum[a[x]]*sum[a[x]];
	sum[a[x]]--;
	cnt+=sum[a[x]]*sum[a[x]];
}
bool cmp(node x,node y)
{
	if(x.bl!=y.bl) return x.l<y.l;
	else
	{
		if(x.bl&1) return x.r<y.r;
		else return x.r>y.r;
	}
}
int main( )
{
//	ios::sync_with_stdio(false);
	scanf("%d%d%d",&n,&m,&k);
	block=sqrt(n);
	for(int i=1;i<=n;i++) scanf("%d",&a[i]);
	for(int i=1;i<=m;i++)
	{
		int l,r;
		scanf("%d%d",&l,&r);
		p[i]=node{l,r,i,(l-1)/block+1};
	}
	sort(p+1,p+1+m,cmp);
	int l=1,r=0;
	for(int i=1;i<=m;i++)
	{
		int ll=p[i].l,rr=p[i].r;
		while(l<ll) del(l++);
		while(l>ll) add(--l);
		while(r<rr) add(++r);
		while(r>rr) del(r--);
		ans[p[i].id]=cnt;
	}
	for(int i=1;i<=m;i++) 
	    printf("%d\n",ans[i]);
	return 0;
}
代码2( 卡常 + O2 )
//#pragma GCC optimize(2) 
//#pragma GCC optimize(3) 
#include<cstdio>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxn=1e5+10;
int n,m,k,block,cnt,sum[maxn],a[maxn],ans[maxn];
struct node
{
	int l;
	int r;
	int id;
	int bl;
}p[maxn];
void add(int x)
{
	cnt-=sum[a[x]]*sum[a[x]];
	sum[a[x]]++;
	cnt+=sum[a[x]]*sum[a[x]];
}
void del(int x)
{
	cnt-=sum[a[x]]*sum[a[x]];
	sum[a[x]]--;
	cnt+=sum[a[x]]*sum[a[x]];
}
bool cmp(node x,node y)
{
	if(x.bl!=y.bl) return x.l<y.l;
	else
	{
		if(x.bl&1) return x.r<y.r;
		else return x.r>y.r;
	}
}
int main( )
{
//	ios::sync_with_stdio(false);
	scanf("%d%d%d",&n,&m,&k);
	block=sqrt(n);
	for(register int i=1;i<=n;++i) scanf("%d",&a[i]);
	for(register int i=1;i<=m;++i)
	{
		int l,r;
		scanf("%d%d",&l,&r);
		p[i]=node{l,r,i,(l-1)/block+1};
	}
	sort(p+1,p+1+m,cmp);
	int l=1,r=0;
	for(register int i=1;i<=m;++i)
	{
		int ll=p[i].l,rr=p[i].r;
		while(l<ll) del(l++);
		while(l>ll) add(--l);
		while(r<rr) add(++r);
		while(r>rr) del(r--);
		ans[p[i].id]=cnt;
	}
	for(register int i=1;i<=m;++i) 
	    printf("%d\n",ans[i]);
	return 0;
}
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值