1277 字符串中的最大值 (kmp)

来源:互联网 发布:淘宝虚拟代理挣钱吗 编辑:程序博客网 时间:2024/06/08 02:09


1277 字符串中的最大值
题目来源: Codility
基准时间限制:1 秒 空间限制:131072 KB 分值: 80 难度:5级算法题
 收藏
 关注
一个字符串的前缀是指包含该字符第一个字母的连续子串,例如:abcd的所有前缀为a, ab, abc, abcd。
给出一个字符串S,求其所有前缀中,字符长度与出现次数的乘积的最大值。
例如:S = "abababa" 所有的前缀如下:
 
"a", 长度与出现次数的乘积 1 * 4 = 4,
"ab",长度与出现次数的乘积 2 * 3 = 6,
"aba", 长度与出现次数的乘积 3 * 3 = 9,
"abab", 长度与出现次数的乘积 4 * 2 = 8,
"ababa", 长度与出现次数的乘积 5 * 2 = 10,
"ababab", 长度与出现次数的乘积 6 * 1 = 6,
"abababa", 长度与出现次数的乘积 7 * 1 = 7.

其中"ababa"出现了2次,二者的乘积为10,是所有前缀中最大的。
Input
输入字符串S, (1 <= L <= 100000, L为字符串的长度),S中的所有字符均为小写英文字母。
Output
输出所有前缀中字符长度与出现次数的乘积的最大值。
Input示例
abababa
Output示例
10

next数组的含义: next【i】 表示当前匹配到第i个字符,前缀与后缀的最长公共长度. 

这里可以理解为以i结尾的前缀包含 长度为next【i】的前缀


注意算出next要倒着扫,因为前面的前缀,可能由后面增加...倒着扫的思想很常用

#include <iostream>#include <cstring>#include <cstdio>#include <algorithm>using namespace std;typedef long long ll;const int maxn = 1e5 + 5;int next[maxn];char s[maxn];ll cnt[maxn];void compute_prefix(int *next, char *p){    int n, k;    n = strlen(p);    next[0] = next[1] = 0;    k = 0;    for(int i = 2; i <= n; i++)    {        while(k && p[k] != p[i-1])            k = next[k];             if(p[k] == p[i-1])            k++;        next[i] = k;    }}int main(){    cin >> s;    int len = strlen(s);    compute_prefix(next, s);//    cout << 1 << endl;    for(int i = len; i >= 1; i--)    {        cnt[i]++;        cnt[next[i]] += cnt[i];    }    ll ans = -1;    for(int i = 1; i <= len; i++)        ans = max(ans, cnt[i]*(ll)i);    cout << ans << endl;    return 0;}


阅读全文
0 0