Prefix Substring (2018年徐州矿大亚洲区邀请赛热身赛)

时间:2021-07-25 00:06:43

Given two stringA ,B,how many sustring of A is prefix_substring of B ? Two substring are considered different if their first or last orboth indexes in A are different

Input

 Multiple test cases , the number of test cases will be no more than 10

 Each test cases contians two lines . The first line contions string A ,the second line contions a string B (1<=|A|,|B|<=1e5)

A and B only contions lowercase English

Output

 For each test cases ,output an integer ,the number of different substring which are prefix-sustring of B

Example

input

a

a

cab

abd

output

1

2

思路:EXKMP模板

AC:代码

优秀博客 传送门

#include <bits/stdc++.h>

using namespace std;

const int maxn=100010; 
int next[maxn],ex[maxn];
char a[maxn],b[maxn];
 
void GETNEXT(char *str)  
{  
    int i=0,j,po,len=strlen(str);  
    next[0]=len;  
    while(str[i]==str[i+1]&&i+1<len) 
    i++;  
    next[1]=i;  
    po=1; 
    for(i=2;i<len;i++)  
    {  
        if(next[i-po]+i<next[po]+po) 
        next[i]=next[i-po];  
        else
        {  
            j=next[po]+po-i;  
            if(j<0)j=0;
            while(i+j<len&&str[j]==str[j+i])
            j++;  
            next[i]=j;  
            po=i;
        }  
    }  
}  

void EXKMP(char *s1,char *s2)  
{  
    int i=0,j,po,len=strlen(s1),l2=strlen(s2);  
    GETNEXT(s2); 
    while(s1[i]==s2[i]&&i<l2&&i<len) 
    i++;  
    ex[0]=i;  
    po=0;
    for(i=1;i<len;i++)  
    {  
        if(next[i-po]+i<ex[po]+po)  
        ex[i]=next[i-po];  
        else 
        {  
            j=ex[po]+po-i;  
            if(j<0)j=0; 
            while(i+j<len&&j<l2&&s1[j+i]==s2[j]) 
            j++;  
            ex[i]=j;  
            po=i; 
        }  
    }  
} 

int main()
{
	while(~scanf("%s %s",a,b))
	{
		EXKMP(a,b);
		int s = 0;
		int len = strlen(a);
		for(int i = 0;i<len;i++){
			s += ex[i];
		}
		printf("%d\n",s);
	}
	return 0;
}