您的位置:首页 > 其它

codeforces #307 E. GukiZ and GukiZiana (分块)

2015-10-20 13:46 495 查看
题目:http://codeforces.com/problemset/problem/551/E

题意:给定n个元素的数组,然后操作q次。有两种操作:1、1 l r x 操作类型为1,将[l,r]的所有元素+x 。2、2 x 查询整个区间的最左和最右边的x的距离d1和d2,求d2-d1,不存在x输出-1。

分析:第一次写分块。。。思路很简单,就是将整个数组分成很多块。在cf上看到一份十分简洁的ac代码,参考了一下。

现在考虑时间复杂度。

对于操作1,首先会遍历sqrt(n)个块,然后最多对两个块里面的所有元素(sqrt(n)个)进行遍历(对于完全包含的区间懒惰标记即可),最后还要对完全遍历的块排序,操作1的时间复杂度为O(sqrt(n)+log(sqrt(n)))

对于操作2,同样会遍历sqrt(n)个块,然后对每个块里面的sqrt(n)个元素进行二分查找两次O(log(sqrt(n))),所以操作2的时间复杂度O(sqrt(n)*log(sqrt(n)))

所以总的时间复杂度为O(q*sqrt(n)*log(sqrt(n)))。

代码:

#include <bits/stdc++.h>
using namespace std;

typedef long long LL;
typedef unsigned long long ULL;
const LL INF = 1E9+9;
const int maxn = 1e6+7;
const int D=1000;
pair <LL ,int > p[maxn];
LL v,lazy[maxn];

int main()
{
int n,q,i,j,l,r,x,y,a,b,t;
scanf("%d%d",&n,&q);
for(i=1;i<=n;i++)
{
scanf("%lld",&v);
p[i]=make_pair(v,i);
}
for(i=1;i<=n;i+=D)
sort(p+i,p+min(i+D,n+1));
while(q--)
{
int tp;
scanf("%d",&tp);
if(tp==1)
{
scanf("%d%d%d",&a,&b,&x);
for(l=1,t=1;l<=n;l+=D,t++)
{
r=min(l+D-1,n);
if(a>r || b<l)
continue ;
if(a<=l && r<=b)
{
lazy[t]+=x;
continue ;
}
for(i=l;i<=r;i++)
if(a<=p[i].second && p[i].second<=b)
p[i].first+=x;
sort(p+l,p+r+1);
}
}
else
{
scanf("%d",&x);
int L=n+1,R=0;
for(l=1,t=1;l<=n;l+=D,t++)
{
LL fd=x-lazy[t];
r=min(l+D-1,n);
int p1=lower_bound(p+l,p+r+1,make_pair(fd,0))-p;
int p2=lower_bound(p+l,p+r+1,make_pair(fd+1,0))-p-1;
if(p1<=p2)
{
L=min(L,p[p1].second);
R=max(R,p[p2].second);
}
}
L<=R?printf("%d\n",R-L):printf("-1\n");
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  codefroces 分块