跳到正文

题解

题解:AT_abc452_g [ABC452G] 221 Substring

wzhm54nr约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年4月7日
收录
2026年4月7日
更新
2026年11月18日
篇幅
约 3 分钟

版本

  1. v1当前

废话

ABC 最近怎么把蓝题吃了,F 放绿 G 放紫。

思路

一段极长的相同数字的连续子串可以分为以下 33 种:

  1. 不能碰:长度太短,你不能在任何合法的答案中包含它。
  2. 可以碰但不能越过:长度太长,所以只能出现在合法串的开头或结尾。
  3. 可以越过:长度正好,可以出现在开头、结尾或中间。

原题定义的合法串太不简洁,我们把一段极长的相同数字串缩成一个数字,可以证明这样能和原合法串一一对应。我们定义字符 0 表示不许碰到,那么三条约束即表示如下:

  1. 0:不能用。
  2. x0x:要么作为结尾(不许向右扩展),要么作为开头(不许向左扩展)。
  3. x:随便用。

问题即转为求转化后的串有多少不含 0 的本质不同的子串。P2408 即可。

代码

给出 SAM 的代码。

C++
#include<bits/stdc++.h>
using namespace std;
const int N=1.5e6+5;
// (color,count)
vector<pair<int,int> > v;
int n,a[N];
int ch[N][10],fa[N],len[N],lst=1,cnt=1;
long long f[N];
void insert(int c){
	int cur=++cnt;len[cur]=len[lst]+1;
	for(;lst&&!ch[lst][c];lst=fa[lst])  ch[lst][c]=cur;
	if(!lst)  fa[cur]=1;
	else{
		int p=lst,q=ch[lst][c];
		if(len[p]+1==len[q])  fa[cur]=q;
		else{
			int cl=++cnt;
			fa[cl]=fa[q],len[cl]=len[p]+1,fa[cur]=fa[q]=cl;
			memcpy(ch[cl],ch[q],40);
			for(;lst&&ch[lst][c]==q;lst=fa[lst])  ch[lst][c]=cl;
		}
	}
	lst=cur;
}
long long dfs(int u){
	if(f[u])  return f[u];
	for(int i=1;i<=9;i++)if(ch[u][i])  f[u]+=1+dfs(ch[u][i]);
	return f[u];
}
signed main(){
	scanf("%d",&n);
	for(int i=1,x;i<=n;i++){
		scanf("%d",&x);
		if(!v.empty()&&x==v.back().first)  ++v.back().second;
		else  v.push_back({x,1});
	}
	n=0;
	for(auto[x,c]:v){
		if(c<x)  a[++n]=0;
		else if(c==x)  a[++n]=x;
		else  a[++n]=x,a[++n]=0,a[++n]=x;
	}
	for(int i=1;i<=n;i++)  insert(a[i]);
	printf("%lld\n",dfs(1));
	return 0;
}
原文
存档评论1 条抓取于