您的位置:首页 > 其它

bzoj 3809: Gty的二逼妹子序列 分块+莫队算法

2016-11-17 15:06 405 查看

题意

给出n个数m次询问,每次询问[a,b]之间的颜色在区间[l,r]之间出现了多少种。

n<=100000,m<=1000000

分析

看到28M的内存整个人都不好了啊。

树套树什么的就别想了~~

这题很容易想到莫队+树状数组,那样的话复杂度是O(nn√logn)

还有一种离奇的分块做法,就是对权值分块,那么修改就是O(1),查询就是O(nn√)

那么总复杂度就是O(nn√)了

好劲啊居然跑了40s+,不过我看到居然还有跑了80s+的……

卡常出奇迹啊~~

代码

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#define N 100005
#define M 350
#define Q 1000005
using namespace std;

int pos
,sta[M],end[M],t
,sum[M],n,m,a
,block;
struct que{int l,r,a,b,ans,id;}q[Q];

int read()
{
int x=0,f=1;char ch=getchar();
while (ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while (ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}

bool cmp(que a,que b)
{
return pos[a.l]<pos[b.l]||pos[a.l]==pos[b.l]&&a.r<b.r;
}

bool cmpid(que a,que b)
{
return a.id<b.id;
}

void updata(int x,int y)
{
if (y==1)
{
t[x]++;
if (t[x]==1) sum[pos[x]]++;
}else
{
t[x]--;
if (t[x]==0) sum[pos[x]]--;
}
}

int query(int l,int r)
{
if (pos[l]==pos[r])
{
int tot=0;
for (int i=l;i<=r;i++)
if (t[i]) tot++;
return tot;
}
int tot=0;
for (int i=pos[l]+1;i<pos[r];i++)
tot+=sum[i];
for (int i=l;i<=end[pos[l]];i++)
if (t[i]) tot++;
for (int i=sta[pos[r]];i<=r;i++)
if (t[i]) tot++;
return tot;
}

void solve()
{
int l=1,r=1;
updata(a[1],1);
for (int i=1;i<=m;i++)
{
for (;r<q[i].r;r++)
updata(a[r+1],1);
for (;l>q[i].l;l--)
updata(a[l-1],1);
for (;r>q[i].r;r--)
updata(a[r],-1);
for (;l<q[i].l;l++)
updata(a[l],-1);
q[i].ans=query(q[i].a,q[i].b);
}
}

int main()
{
//freopen("3809.in","r",stdin);freopen("test.out","w",stdout);
n=read();m=read();
block=sqrt(n);
for (int i=1;i<=n;i++)
{
a[i]=read();
pos[i]=(i+block-1)/block;
if (!sta[pos[i]]) sta[pos[i]]=i;
end[pos[i]]=i;
}
for (int i=1;i<=m;i++)
{
q[i].l=read();q[i].r=read();q[i].a=read();q[i].b=read();
q[i].id=i;
}
sort(q+1,q+m+1,cmp);
solve();
sort(q+1,q+m+1,cmpid);
for (int i=1;i<=m;i++)
printf("%d\n",q[i].ans);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: