莫队实在卡不过去了!TLE on #29 I NEED HELP!
查看原帖
莫队实在卡不过去了!TLE on #29 I NEED HELP!
484780
husy楼主2022/8/20 11:45
#pragma GCC optimize (3)
#pragma GCC optimize ("Ofast")
#include<bits/stdc++.h>
using namespace std;
int n,m,b[500010];
int a[500010];
struct node
{
	int l,r,id;
}q[500010];
int sz,block[500010],st[500010],top,pos[500010];
int ans[500010],siz;
inline void read(int &x){
	x = 0;
	char c = getchar();
	while(c<'0'||c>'9') c = getchar();
	while(c>='0'&&c<='9'){
		x = (x<<3)+(x<<1)+(c^48);
		c = getchar();
	}
} 
void print(int x){
	if(x>9) print(x/10);
	putchar(x%10+'0');
}
bool cmp(node a,node b)
{
	 return (block[a.l]^block[b.l])?a.l<b.l:((block[a.l]&1)?a.r<b.r:a.r>b.r);
}
void add(int x)
{
	++b[a[x]];
	if(b[a[x]]==1)
	{
		st[++top]=a[x];
		pos[a[x]]=top;
	}
	else if(b[a[x]]==2)
	{
		st[pos[a[x]]]=st[top];
		pos[st[top]]=pos[a[x]];
		st[top--]=pos[a[x]]=0;
	}
}
void del(int x)
{
	--b[a[x]];
	if(b[a[x]]==1)
	{
		st[++top]=a[x];
		pos[a[x]]=top;
	}
	else if(b[a[x]]==0)
	{
		st[pos[a[x]]]=st[top];
		pos[st[top]]=pos[a[x]];
		st[top--]=pos[a[x]]=0;
	}
}
void solve()
{
	int l=1,r=0;
	for(int i=1;i<=m;i++)
	{
		int ql=q[i].l,qr=q[i].r;
		while(ql<l)--l,add(l);
		while(ql>l)del(l),++l;
		while(qr<r)del(r),--r;
		while(qr>r)++r,add(r);
		ans[q[i].id]=st[top];
	}
	for(int i=1;i<=m;i++)print(ans[i]),puts("");
}
int main()
{
	read(n);
	siz=sqrt(n);
	for(int i=1;i<=n;i++)read(a[i]),block[i]=i/siz+1;
	read(m);
	for(int i=1;i<=m;i++)read(q[i].l),read(q[i].r),q[i].id=i;
	sort(q+1,q+m+1,cmp);
	solve();
	return 0;
}
2022/8/20 11:45
加载中...