跳到正文

题解

[广义 SAM] CF427D Match & Catch

Claysonleet约 4 分钟
原文

这是 2026年4月23日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2022年4月29日
收录
2026年4月23日
更新
2026年11月5日
篇幅
约 4 分钟
题目
CF427D

版本

  1. v2当前
  2. v1

考虑建立 广义 SAM, 然后看节点 uu 是否满足 :sizu,0=sizu,1=1siz_{u,0} = siz_{u, 1} = 1

如果满足, 可以考虑 :minlenu=maxlen(fau)+1minlen_u = maxlen(fa_u) + 1 , 然后直接对其 maxlen(fau)+1maxlen(fa_u) + 1 取 minmin 即可。

时间复杂度 O(n∗26)O(n * 26) :

CODE :

C++
#include<bits/stdc++.h>

using namespace std;

const int N = 1e5 + 5;

int ans = N;

struct SAM {
	char s[N];
	int n, tot = 1, lst = 1, cnt = 0;
	int fa[N], ll[N], ch[N][27], siz[N][2], hd[N];
	inline void insert (int pos, char c, int MODE) {
		int v = lst, u = ++ tot, x = v, y, idx = c - 'a';
		lst = u, siz[u][MODE] = 1, ll[u] = pos;
		for ( ; x && ! ch[x][idx]; x = fa[x]) ch[x][idx] = u;
		y = ch[x][idx]; 
		if (! x) {
			fa[u] = 1; return ;
		}
		else if (ll[y] == ll[x] + 1) { fa[u] = y; return ; }
		else {
			int p = ++ tot;
			ll[p] = ll[x] + 1, fa[p] = fa[y], fa[u] = fa[y] = p;
			for (int i = 0; i < 26; i ++) ch[p][i] = ch[y][i];
			for ( ; x && ch[x][idx] == y; x = fa[x]) ch[x][idx] = p;
		}
		return ;
	} 
	struct EDGE {
		int v, nxt;
	} e[N * 2];
	inline void link_edge (int u, int v) { e[++ cnt] = {v, hd[u]}, hd[u] = cnt; }
    inline void init () {
		n = 0, tot = 1, lst = 1, cnt = 0;
		memset(ch, 0, sizeof(ch)), memset(ll, 0, sizeof(ll));
		memset(fa, 0, sizeof(fa)), memset(hd, 0, sizeof(hd));
        memset(siz, 0, sizeof(siz));
	}
	inline void build_sam () {
        init();
		scanf("%s", s + 1), n = strlen(s + 1);
		for (int i = 1; i <= n; i ++) insert(i, s[i], 0);
		scanf("%s", s + 1), n = strlen(s + 1), lst = 1;
		for (int i = 1; i <= n; i ++) insert(i, s[i], 1);
		for (int i = 2; i <= tot; i ++) link_edge(fa[i], i);
	}
	inline void dfs (int u) {
		for (int i = hd[u]; i; i = e[i].nxt) {
			dfs(e[i].v);
			siz[u][0] += siz[e[i].v][0], siz[u][1] += siz[e[i].v][1];
		}
		if (siz[u][1] == 1 && siz[u][0] == 1 && fa[u] != 0) ans = min(ans, (ll[fa[u]] + 1));
		return ;
	}	
} sam;
int main() {
	sam.build_sam(), sam.dfs(1);
	if (ans == N) cout << -1;
	else cout << ans;
	return 0;
}