【loj6282】数列分块练习 6

「分块」数列分块入门1 – 9 by hzwer

#include
#include
#include
#include
#include
#include
#define inf 0x3f3f3f3f
#define N 1000009
#define ll long long
using namespace std;

vector vec[2006];
ll v[N];
int L[N],R[N],blo[N],st[N];
int n,m,len;


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

pair query(int x)
{
	int i=1;
	while(x>vec[i].size())
		x-=vec[i].size(),i++;
	return make_pair(i,x-1);
}

void rebuild()
{
	int top=0;
	for (int i=1;i<=m;i++)
	{
		for (vector::iterator j=vec[i].begin();j!=vec[i].end();j++) st[++top]=*j;
		vec[i].clear();
	}
	int len2=sqrt(top);
	for (int i=1;i<=top;i++)
		vec[(i-1)/len2+1].push_back(st[i]);
	m=(top-1)/len2+1;
}

void insert(int l,int r)
{
	pair t=query(l);
	vec[t.first].insert(vec[t.first].begin()+t.second,r);
	if (vec[t.first].size()>20*len) rebuild();
}

int main()
{
	n=read();len=sqrt(n);
	for (int i=1;i<=n;i++) v[i]=read();
	for (int i=1;i<=n;i++) vec[(i-1)/len+1].push_back(v[i]);
	m=(n-1)/len+1;
	for (int i=1;i<=n;i++)
	{
		int opt=read(),l=read(),r=read();ll d=read();
		if (!opt) insert(l,r);
		else
		{
			pair t=query(r);
			printf("%lld\n",vec[t.first][t.second]);
		}

	}

	return 0;
}

你可能感兴趣的:(LibreOJ,中级数据结构-分块)