牛牛和字符串的日常

链接:https://ac.nowcoder.com/acm/contest/11334/G
来源:牛客网

题目描述
牛牛每天都要做的事就是读书,从书里找自己喜欢的句子,他每天都会去读一本书,如果牛牛今天读的书的某连续{}kk个字符刚好是牛牛喜欢句子的某个前缀,那么牛牛将得到{}kk点兴奋感,但他每天只能注意到一次自己喜欢的句子(也就是每天只能增加一次兴奋感),也就是说他会尽量去找那个让自己兴奋度增加最多的句子,那么,{}nn天之后牛牛总共最多能有多少兴奋感?

输入描述:
第一行是一个字符串s(|s|<=1×10^5)表示牛牛喜欢的字符串第一行是一个字符串s(∣s∣<=1×10
5
)表示牛牛喜欢的字符串

第二行是一个整数n,表示总共经历了n天(n<=100){}第二行是一个整数n,表示总共经历了n天(n<=100)
接下来n行每行一个字符串t_i(|t_i|<=1×10^5),分别表示牛牛第i天读的书接下来n行每行一个字符串t
i

(∣t
i

∣<=1×10
5
),分别表示牛牛第i天读的书
输出描述:
输出这n天来牛牛最大能获得的兴奋感

示例1
输入
复制
abcdefg
3
adcabc
xyz
abdefg
输出
复制
5
说明
第一天有"a",“abc"可以增加兴奋度,选择"abc”,第二天没有,第三天有"ab",总共为5

看每个字符串最多能匹配到模式串的哪里

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;
const int N = 1e5 + 10;

int ne[N];

int main(){
    
    
	char str[N];
	cin >> str + 1;
	
	int len = 1;
	while(str[len])   len ++;
	
	for (int i = 2, j = 0; i < len; i ++){
    
    
		while(j && str[i] != str[j + 1])   j = ne[j];
		if (str[i] == str[j + 1])    ne[i] = j;
		j = ne[j];
	}
	
	int n;
	long long ans = 0;
	scanf("%d", &n);
	
	for (int i = 1; i <= n; i ++){
    
    
		int cnt = 0;
		char s[N];
		cin >> s + 1;
		int len = 1;
		while(s[len])  len ++;
		for (int i = 1, j = 0; i < len; i ++){
    
    
			while(j && s[i] != str[j + 1])   j = ne[j];
			if (s[i] == str[j + 1])   j ++;
			cnt = max(cnt, j);
		}
		ans += cnt;
	}
	
	cout << ans << endl;
}

猜你喜欢

转载自blog.csdn.net/qq_45772483/article/details/112557985