跳到正文

题解

题解:P6864 [RC-03] 记忆

Little_Cake_qwq约 4 分钟
原文
文章信息与版本

文章信息

收录
2026年1月1日
更新
2026年1月1日
篇幅
约 4 分钟
题目
P6864

版本

  1. v2当前
  2. v1

练专题时有大佬给我们讲这道题,来写篇题解加深理解。

思路

设当前字符串的非空子串个数为 xx,结尾的非空子串个数为 yy。则操作一后,y′=y+1y'=y+1,x′=x+y+1x'=x+y+1;而操作二后,y′=1y'=1,x′=x+1x'=x+1。 容易发现,对于操作一和操作二,都是可以用矩阵乘法来表示,操作一的矩阵变为:

[100110111]\begin{bmatrix}1&0&0\\1&1&0\\1&1&1\end{bmatrix}

而操作二的矩阵为:

[100000111]\begin{bmatrix}1&0&0\\0&0&0\\1&1&1\end{bmatrix}

而对于操作三或是还没轮到的操作,由于是没有了,所以矩阵为:

[100010001]\begin{bmatrix}1&0&0\\0&1&0\\0&0&1\end{bmatrix}

答案即为 [111]\begin{bmatrix}1&1&1\end{bmatrix} 乘所有矩阵。 由于矩阵乘法满足结合律,所以考虑用线段树维护,时间复杂度 O(qlog⁡n)O(q\log n)。

进食后人:不开 long long 见祖宗!

代码

C++
const int N=2e5+8;
int q;
int c[N],o[N],p[N];
struct node
{
	int l,r;
	int n=0,m=0,a[4][4];
	void init()
	{
		for(int i=1;i<=3;i++)
			for(int j=1;j<=3;j++)
				a[i][j]=0;
	}//初始化
	void add1()
	{
		n=m=3;
		a[1][1]=a[2][1]=a[2][2]=a[3][1]=a[3][2]=a[3][3]=1;
	}//操作一
	void add2()
	{
		n=m=3;
		a[1][1]=a[3][1]=a[3][2]=a[3][3]=1;
	}//操作二
	void no()
	{
		n=m=3;
		a[1][1]=a[2][2]=a[3][3]=1;
	}//没有
}t[4*N];
void push_up(node &f,node x,node y)
{
	f.init();
	f.n=x.n;f.m=y.m;
	for(int i=1;i<=x.n;i++)
		for(int k=1;k<=x.m;k++)
			for(int j=1;j<=y.m;j++)
				f.a[i][j]+=x.a[i][k]*y.a[k][j];
}
void build(int o,int x,int y)
{
	t[o].l=x,t[o].r=y;
	if(x==y)
	{
		t[o].init(),t[o].no();
		return ;
	}
	int mid=(t[o].l+t[o].r)>>1,ls=o<<1,rs=o<<1|1;
	build(ls,x,mid);
	build(rs,mid+1,y);
	push_up(t[o],t[ls],t[rs]);
}
void update(int o,int x,int opt)
{
	if(x==t[o].l&&x==t[o].r)
	{
		t[o].init();
		if(opt<0) t[o].no();
		else if(opt==1) t[o].add1();
		else  t[o].add2();
		return ;
	}
	int mid=(t[o].l+t[o].r)>>1,ls=o<<1,rs=o<<1|1;
	if(x<=mid) update(ls,x,opt);
	else update(rs,x,opt);
	push_up(t[o],t[ls],t[rs]);
}
signed main()
{
	ios::sync_with_stdio(0);cin.tie(0),cout.tie(0);
	cin>>q;
	build(1,1,q);
	for(int i=1;i<=q;i++)
	{
		int opt;cin>>opt;
		if(opt==1) p[i]=c[i]=i,o[i]=1,update(1,p[i],o[i]);
		else if(opt==2) p[i]=c[i]=i,o[i]=2,update(1,p[i],o[i]);
		else
		{
			cin>>c[i];
			p[i]=p[c[i]];
			o[i]=-o[c[i]];
			update(1,p[i],o[i]);
		}
		node res;
		res.n=1,res.m=3;
		res.init();
		res.a[1][1]=res.a[1][2]=res.a[1][3]=1;
		push_up(res,res,t[1]);
		cout<<res.a[1][1]<<'\n';
	}
	return 0;
}
原文