hdu3294 Manacher算法模板

题目链接:http://icpc.njust.edu.cn/Problem/Hdu/3294/

回文长度如果是mxx,回文中心是id的话,在扩展串中(id-mxx+1,id+mxx-1)的这段中去除标记符号的部分就是回文串。还有个注意点就是错位循环赋值的问题。

代码如下:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 typedef unsigned int ui;
 4 typedef long long ll;
 5 typedef unsigned long long ull;
 6 #define pf printf
 7 #define mem(a,b) memset(a,b,sizeof(a))
 8 #define prime1 1e9+7
 9 #define prime2 1e9+9
10 #define pi 3.14159265
11 #define lson l,mid,rt<<1
12 #define rson mid+1,r,rt<<1|1
13 #define scand(x) scanf("%llf",&x) 
14 #define f(i,a,b) for(int i=a;i<=b;i++)
15 #define scan(a) scanf("%d",&a)
16 #define dbg(args) cout<<#args<<":"<<args<<endl;
17 #define inf 0x3f3f3f3f
18 #define maxn 200010
19 int n,m,t;
20 char s[maxn],ma[maxn<<1];
21 int Len[maxn<<1];
22 int mxx,id;//最大回文半径和中心 
23 void init(char c,char* s)
24 {
25     int len=strlen(s);
26     f(i,0,len-1)
27     {
28         s[i]=(char)('a'+(s[i]-c+26)%26);
29     }
30 }
31 void manacher(char* s,int len)
32 {
33     int l=0;
34     ma[l++]='$';
35     ma[l++]='#';
36     f(i,0,len-1)
37     {
38         ma[l++]=s[i];
39         ma[l++]='#';
40     }
41     ma[l]=0;
42     int pos=0,mr=0;
43     mxx=0;
44     f(i,0,l-1)
45     {
46         Len[i]=(mr>i)?min(mr-i,Len[2*pos-i]):1;
47         while(ma[i+Len[i]]==ma[i-Len[i]])Len[i]++; 
48         if(i+Len[i]>mr)mr=i+Len[i],pos=i;
49         if(Len[i]-1>mxx)
50         {
51             mxx=Len[i]-1;
52             id=i;
53         }
54     }
55 }
56 int main()
57 {
58     //freopen("input.txt","r",stdin);
59     //freopen("output.txt","w",stdout);
60     std::ios::sync_with_stdio(false);
61     char c;
62     while(scanf(" %c %s",&c,s)==2)
63     {
64         init(c,s);
65         int len=strlen(s);
66         int ansl=0,ansr=0;
67         manacher(s,len);
68         if(mxx==1)pf("No solution!\n");//回文长度是1 
69         else 
70         {
71             int l=(id-mxx+1)/2-1;
72             int r=(id+mxx-1)/2-1;
73             pf("%d %d\n",l,r);
74             f(i,l,r)pf("%c",s[i]);
75             pf("\n");
76 //            f(i,id-mxx+1,id+mxx-1)pf("%c",ma[i]);
77 //            pf("\n");
78         }
79     }
80  } 

猜你喜欢

转载自www.cnblogs.com/randy-lo/p/12521212.html