K - Strings in the Pocket (马拉车模板)

 

 AC_Code:

 1 #include <iostream>
 2 #include <bits/stdc++.h>
 3 using namespace std;
 4 typedef long long ll;
 5 const int maxn = 2e6+10;
 6 const int inf = 0x3f3f3f3f;
 7 #define rep(i,first,second) for(int i=first;i<=second;i++)
 8 #define dep(i,fisrt,second) for(int i=first;i>=second;i--)
 9 
10 char s[maxn],t[maxn];
11 char tmp[maxn<<1];
12 ll Len[maxn<<1];//存放以 i-th 字符为中心的最长回文子串的长度
13 int len;
14 
15 bool check(int l,int r){
16     for(int i=l,j=r;i<=r;i++,j--){
17         if( s[i]!=t[j] ){
18             return false;
19         }
20     }
21     return true;
22 }
23 
24 void manacher(){
25     ll mx=0,mid=0;
26 //    ll maxlen=-1;
27     rep(i,1,len-1){
28         if( i<mx ) Len[i]=min(Len[2*mid-i],mx-i);
29         else Len[i]=1ll;
30         while( tmp[i-Len[i]]==tmp[i+Len[i]]){
31             Len[i]++;
32         }
33         if( mx<i+Len[i] ){
34             mid=i;
35             mx=i+Len[i];
36         }
37 //        maxlen = max(maxlen,Len[i]-1);
38     }
39 //    printf("%lld\n",maxlen);
40 }
41 
42 ll init(){
43     tmp[0]='@';
44     tmp[1]='#';
45     int j=2;
46     rep(i,0,len-1){
47         tmp[j++]=s[i];
48         tmp[j++]='#';
49     }
50     tmp[j]=')';
51     len=j;
52     manacher();
53     ll ans=0;
54     for(int i=0;i<j;i++){
55         ans+=Len[i]/2ll;
56     }
57     return ans;
58 }
59 
60 int main()
61 {
62     int T;
63     scanf("%d",&T);
64     while( T-- ){
65         scanf("%s%s",s,t);
66         len=strlen(s);
67         int l=-1,r=-1;
68         int f=1;
69         rep(i,0,len-1){
70             if( s[i]!=t[i] ){
71                 f=0;
72                 if( l==-1 ) l=i;
73                 r=i;
74             }
75         }
76 
77         ll ans;
78         if( !f ){
79             if( !check(l,r) ) ans=0;
80             else{
81                 ans=1;
82                 for(int i=r+1,j=l-1;i<len,j>=0;i++,j--){
83                     if( s[i]==s[j] ){
84                         ans++;
85                     }
86                     else break;
87                 }
88             }
89         }
90         else ans=init();
91         printf("%lld\n",ans);
92     }
93     return 0;
94 }

猜你喜欢

转载自www.cnblogs.com/wsy107316/p/12698956.html