跳到正文

个人记录

题解:动物园

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

文章信息

收录
2026年2月3日
更新
2026年2月6日
篇幅
约 4 分钟

版本

  1. v2当前
  2. v1

最劣解题解🤣🤣🤣

先看暴力。

C++
void get_pre(){
	pre[0] = pre[1] = 0;
	for (int i = 2; i <= len; i++){
		int j = pre[i - 1];
		while(j && s[j + 1] != s[i]) j = pre[j];
		if (s[j + 1] == s[i]) ++j;
		pre[i] = j;
	}
}
main(){
	cin >> T;
	while (T--){
		init();
		get_pre();
		for (int i = 2; i <= len; i++){
			int j = pre[i];
			while (j){
				while(j && j > i / 2) j = pre[j];
				if (j){
					++num[i];
				}
				j = pre[j];
			}
		}
//省略求答案
}

分析时间复杂度瓶颈:

  • 找到最大的 pre[j]pre[j] 使得 pre[j]>i2pre[j] > \frac{i}{2}
  • 给 num[i]num[i] 一个一个加上。

分别解决办法:

  • 倍增
  • 记忆化

贴代码 :

C++
#include <bits/stdc++.h>
using namespace std;
#define int long long
constexpr int N = 1e6 + 7, MOD = 1e9 + 7;
int T, len, ans, pre[25][N], num[N], sum[N];

string s;
void init(){
	cin >> s;
	len = s.size();
	s = " " + s;
	ans = 1;
	memset(pre, 0, sizeof pre);
	memset(num, 0, sizeof num);
	memset(sum, 0, sizeof sum);
}
void get_pre(){
	pre[0][0] = pre[0][1] = 0;
	for (int i = 2; i <= len; i++){
		int j = pre[0][i - 1];
		while(j && s[j + 1] != s[i]) j = pre[0][j];
		if (s[j + 1] == s[i]) ++j;
		pre[0][i] = j;
	}
}
int lst(int idx){
	int idxx = idx;
	for (int i = 20; i >= 0; i--){
		if (pre[0][pre[i][idx]] >= idxx / 2) idx = pre[i][idx];
	}
	if (pre[0][idx] > idxx / 2) idx = pre[0][idx];
	return idx;
}
int dfs(int j, int idx){
	if (!j) return 0;
	if (j > idx / 2) return dfs(pre[0][lst(idx)], idx);
	if (sum[j]) return sum[j];
	return sum[j] = dfs(pre[0][j], idx) + 1;
}
main(){
	ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	cin >> T;
	while (T--){
		init();
		get_pre();
		for (int i = 1; i <= 20; i++){
			for (int j = 1; j <= len; j++){
				pre[i][j] = pre[i - 1][pre[i - 1][j]];
			}
		}
		for (int i = 2; i <= len; i++){
			int j = pre[0][i];
			num[i] = dfs(j, i);
		}
		for (int i = 1; i <= len; i++){
			ans = (ans * (num[i] + 1)) % MOD;
		}
		cout << ans << "\n";
	}
}
原文