Link:https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1277
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
/*
51nod 1277 字符串中的最大值
求前缀在字符串出现的次数 (num[i])
num[nex[i]] += num[i];
*/
const int N = 100010;
char s[N];
int nex[N];
void getnext(){
int len = strlen(s);
int k = -1;
nex[0] = -1;
for(int i = 1; i < len; i++){
while(k!=-1 && s[k+1]!=s[i])
k = nex[k];
if(s[k+1]==s[i])
k++;
nex[i] = k;
}
}
int mp[N];
int main(){
scanf("%s",s);
getnext();
int len = strlen(s);
memset(mp,0,sizeof(mp));
for(int i = len; i >= 1; i--){
mp[i]++;
mp[nex[i-1]+1] += mp[i];
// printf("%d %d \n",i,mp[i]);
}
LL mx = 0;
for(int i = 1; i <= len; i++){
mx = max(mx,(LL)i*(LL)mp[i]);
}
printf("%lld\n",mx);
return 0;
}
本文提供了一种解决51nod1277问题的有效算法,通过KMP算法预处理字符串获得next数组,进而计算出每个前缀出现的次数,并找出出现次数最多的前缀及其对应的最长长度,最终输出该前缀的最大值。

1101

被折叠的 条评论
为什么被折叠?



