【bzoj1878】HH的项链(莫队)

用莫队发现竟然比树状数组要快,是不是可能写树状数组的时候忘记加读入优化了,也是写的第一道莫队算法的题,感觉上莫队算法就是一种比较高端的暴力,去问了钊神确认了一下,莫队算法就是分块离线处理区间询问的问题,大体思路就是如果对于询问的区间左端点右端点+-1能够递推出解的情况,先对询问排序,考虑如果我们不对询问分块的话,我们极有可能被卡,比如1……200000,然后2..3,类似这样的数据就会被卡的很惨。。。。所以我们对于询问所在的块排序,所以左右端点一定只在一个小范围内移动,所以很难构造出能被卡掉的数据,因为分块的大小都是不一定的,所以其实跑起来特别快

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>

using namespace std;

int n,m,blo;
int a[50010];
inline int F()
{
    register int aa,bb;register char ch;
    while(ch=getchar(),(ch<'0'||ch>'9')&&ch!='-');ch=='-'?aa=bb=0:(aa=ch-'0',bb=1);
    while(ch=getchar(),ch>='0'&&ch<='9')aa=(aa<<3)+(aa<<1)+ch-'0';return bb?aa:-aa;
}
struct query{
    int id,l,r,ans;
    bool operator < (const query &rhs)const {
        return l/blo ==rhs.l/blo?r<rhs.r:l/blo<rhs.l/blo;}              
}q[200010];
int ans[200010],cnt[1000010];
int main()
{
    n=F();
    for (int i=1;i<=n;i++)
    a[i]=F();
    m=F();
    blo=n/sqrt(m);
    for (int i=0;i<m;i++)
    {
        int l,r;
        l=F(),r=F();
        q[i].id=i,q[i].l=l,q[i].r=r;
    }
    sort(q,q+m);
    int nowl=q[0].l,nowr=q[0].l-1,nowans=0;
    for (int i=0;i<m;i++)
    {
        while (nowl>q[i].l)nowl--,nowans+=!cnt[a[nowl]],cnt[a[nowl]]++;
        while (nowr<q[i].r)nowr++,nowans+=!cnt[a[nowr]],cnt[a[nowr]]++;
        while (nowr>q[i].r)cnt[a[nowr]]--,nowans-=!cnt[a[nowr]],nowr--;
        while (nowl<q[i].l)cnt[a[nowl]]--,nowans-=!cnt[a[nowl]],nowl++;
        ans[q[i].id]=nowans; 
    }
    for (int i=0;i<m;i++)
    printf("%d\n",ans[i]);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值