string matching
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 630 Accepted Submission(s): 240
Problem Description
String matching is a common type of problem in computer science. One string matching problem is as following:
Given a string s[0…len−1], please calculate the length of the longest common prefix of s[i…len−1] and s[0…len−1] for each i>0.
I believe everyone can do it by brute force.
The pseudo code of the brute force approach is as the following:
We are wondering, for any given string, what is the number of compare operations invoked if we use the above algorithm. Please tell us the answer before we attempt to run this algorithm.Input
The first line contains an integer T, denoting the number of test cases.
Each test case contains one string in a line consisting of printable ASCII characters except space.
* 1≤T≤30
* string length ≤106 for every stringOutput
For each test, print an integer in one line indicating the number of compare operations invoked if we run the algorithm in the statement against the input string.
Sample Input
3 _Happy_New_Year_ ywwyww zjczzzjczjczzzjc
Sample Output
17 7 32
题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=6629
题意:
按照题目所给的代码计算字符串比对次数,实际就是比较母串【0-len】与母串的子串【1-len】。
题解:
扩展kmp板子题,一开始预处理next数组时,将每一位的next求和即可,要记得不想等要+1,因为比较了一次不想等
据说数位dp也能过(这也太硬核了),不能用后缀数组,倍增算法nlogn超时,DC3算法常数过大,同样超时!!
代码:
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn = 1e6+5;
ll t,n,ans;
ll nxt[maxn];
char ch[maxn];
void get_next(char *str) {
int i=0,j,po,len=strlen(str);
nxt[0]=len;//初始化nxt[0]
while(str[i]==str[i+1]&&i+1<len)//计算nxt[1]
i++;
nxt[1]=i;
ans+=nxt[1];
if(nxt[1]!=len-1) {
ans++;
}
po=1;//初始化po的位置
for(i=2; i<len; i++) {
if(nxt[i-po]+i<nxt[po]+po)//第一种情况,可以直接得到nxt[i]的值
nxt[i]=nxt[i-po];
else { //第二种情况,要继续匹配才能得到nxt[i]的值
j=nxt[po]+po-i;
if(j<0)j=0;//如果i>po+nxt[po],则要从头开始匹配
while(i+j<len&&str[j]==str[j+i])//计算nxt[i]
j++;
nxt[i]=j;
po=i;//更新po的位置
}
ans += nxt[i];
if(nxt[i]!=len-i) {
ans++;
}
}
}
int main() {
cin>>t;
while(t--) {
ans = 0;
scanf("%s",ch);
get_next(ch);
cout<<ans<<endl;
}
}