带修改莫队求救
查看原帖
带修改莫队求救
428690
Astatinear楼主2021/11/26 20:41

带修改莫队,TLE82

#include<bits/stdc++.h>
using namespace std;
int n,q,q1,q2;
int a[140005];
int vis[1000005],tot[140005],last[140005];
int change[140005][2];
inline void swap(int &a,int &b)
{
    int x=a;
    a=b;
    b=x;
}
inline int read()
{
	int res = 0;
	char c = getchar();
	while(!isdigit(c)) c = getchar();
	while(isdigit(c)) res = (res << 1) + (res << 3) + (c ^ 48), c = getchar();
	return res;
}
inline void write(int x)
{
    if(x<0){
    	putchar('-');
		x=-x;
	}
    if(x>9) 
		write(x/10);
    putchar(x%10+'0');
}
struct node
{
	int l,r,id,q;
}arr[140005];
inline int cmp(node a,node b)
{
	return (tot[a.l]^tot[b.l])?tot[a.l]<tot[b.l]:((tot[a.r]^tot[b.r])?tot[a.r]<tot[b.r]:a.q<b.q);
}
int ans[140005],now;
int len;
void modify()
{
	for(int i=1;i<=arr[1].q;++i)
	{
		swap(a[change[i][0]],change[i][1]);
	}
	for(int i=arr[1].l;i<=arr[1].r;++i)
	{
		vis[a[i]]++;
		if(vis[a[i]]==1)
		now++;
	}
	ans[arr[1].id]=now;
	int x=arr[1].l,y=arr[1].r,z=arr[1].q;
	for(int i=2;i<=q;++i)
	{
		while(x<arr[i].l)
		now-=!(--vis[a[x++]]);
		while(x>arr[i].l)
		now+=!(vis[a[--x]]++);
		while(y<arr[i].r)
		now+=!(vis[a[++y]]++);
		while(y>arr[i].r)
		now-=!(--vis[a[y--]]);
		while(z<arr[i].q)
		{
			z++;
			if(change[z][0]>=x&&change[z][0]<=y)
			{
				now-=!(--vis[a[change[z][0]]]);
				swap(a[change[z][0]],change[z][1]);
				now+=!(vis[a[change[z][0]]]++);
			}
			else
			{
				swap(a[change[z][0]],change[z][1]);
			}
		}
		while(z>arr[i].q)
		{
			if(change[z][0]>=x&&change[z][0]<=y)
			{
				now-=!(--vis[a[change[z][0]]]);
				swap(a[change[z][0]],change[z][1]);
				now+=!(vis[a[change[z][0]]]++);
			}
			else
			{
				swap(a[change[z][0]],change[z][1]);
			}
			--z;
		}
		ans[arr[i].id]=now;
	}
}
int main()
{
	n=read(),q2=read();
	len=sqrt(n);
	for(int i=1;i<=n;++i)
	{
		a[i]=read();
		last[i]=a[i];
	}
	for(int i=1;i<=q2;++i)
	{
		char x[10];
		int y,z;
		scanf("%s",x);
		y=read(),z=read();
		if(x[0]=='Q')
		{ 
			q++;
			arr[q].id=q,arr[q].q=q1,arr[q].l=y,arr[q].r=z;
		} 
		else 
		{ 
			q1++;
			change[q1][0]=y,change[q1][1]=z;
		} 
	}
	for(int i=1;i<=len;++i)
	{
		for(int j=1;j<=len;++j)
		{
			tot[j+(i-1)*len]=i;
		}
	}
	for(int i=len*len+1;i<=n;++i)
	{
		tot[i]=len+1;
	}
	sort(arr+1,arr+q+1,cmp);
	modify();
	for(int i=1;i<=q;++i)
	{
		write(ans[i]);
		putchar('\n');
	}
	return 0;
}
2021/11/26 20:41
加载中...