luogu P4113 [HEOI2012]采花

背景:

被标签误导(通过标签找题)打了莫队,狂 T L E TLE TLE两个点。
加了优化过不了转树状数组。

题目传送门:

https://www.luogu.org/problemnew/show/P4113

思路:

莫队就是套路。只是过不了。
用树状数组即可,类似于HH的项链
只不过要多记录一个上上个颜色相同的位置。

莫队代码:

#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
	int n,c,m,now=0;
	int p[2000010],block[2000010],hsh[2000010],ans[2000010];
	struct node{int x,y,id;} a[2000010];
bool cmp(node x,node y)
{
	return block[x.x]==block[y.x]?x.y<y.y:x.x<y.x;
}
void move(int x,int d)
{
	if(d==1)
	{
		hsh[x]++;
		if(hsh[x]==2) now++;
	}
	else
	{
		if(hsh[x]==2) now--;
		hsh[x]--;
	}
}
int main()
{
	scanf("%d %d %d",&n,&c,&m);
	int u=sqrt(n);
	for(int i=1;i<=n;i++)
	{
		scanf("%d",&p[i]);
		block[i]=(i-1)/u+1;
	}
	for(int i=1;i<=m;i++)
	{
		scanf("%d %d",&a[i].x,&a[i].y);
		a[i].id=i;
	}
	sort(a+1,a+m+1,cmp);
	int l=1,r=0;
	for(int i=1;i<=m;i++)
	{
		while(l<a[i].x) move(p[l++],-1);
		while(l>a[i].x) move(p[--l],1);
		while(r<a[i].y) move(p[++r],1);
		while(r>a[i].y) move(p[r--],-1);
		ans[a[i].id]=now;
	}
	for(int i=1;i<=m;i++)
		printf("%d\n",ans[i]);
}

树状数组代码:

#include<cstdio>
#include<algorithm>
#define lowbit(x) ((x)&(-(x)))
using namespace std;
	int n,c,m;
	int b[2000010],C[2000010],last[2000010],last_last[2000010],ans[2000010];
	struct node{int x,y,id;} a[2000010];
bool cmp(node x,node y)
{
	return x.y==y.y?x.x<y.x:x.y<y.y;
}
void add(int x,int y)
{
	for(;x<=n;x+=lowbit(x))
		C[x]+=y;
}
int getsum(int x)
{
	int sum=0;
	for(;x;x-=lowbit(x))
		sum+=C[x];
	return sum;
}
int main()
{
	scanf("%d %d %d",&n,&c,&m);
	for(int i=1;i<=n;i++)
		scanf("%d",&b[i]);
	for(int i=1;i<=m;i++)
	{
		scanf("%d %d",&a[i].x,&a[i].y);
		a[i].id=i;
	}
	sort(a+1,a+m+1,cmp);
	int now=1;
	for(int i=1;i<=n;i++)
	{
		if(last[b[i]]) add(last[b[i]],1);
		if(last_last[b[i]]) add(last_last[b[i]],-1);
		last_last[b[i]]=last[b[i]];
		last[b[i]]=i;
		while(i==a[now].y&&now<=m)
		{
			ans[a[now].id]=getsum(a[now].y)-getsum(a[now].x-1);
			now++;
		}
		if(now==m+1) break;
	}
	for(int i=1;i<=m;i++)
		printf("%d\n",ans[i]);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值