usaco Calf Flac(O(n)时间求回文串长度)

来源:互联网 发布:苏州淘宝店铺装修 编辑:程序博客网 时间:2024/06/17 13:26

好高兴,为数不多的我没看题解的题·,我用的是O(n)时间求回文串长度的算法算法在我上一篇博客。

然后就是注意细节了。

/*ID:jinbo wuTASK: calfflacLANG:C++*/#include<bits/stdc++.h>using namespace std;struct node{    char c;    int n;}a[40010];string s;int p[40020];int main(){   freopen("calfflac.in","r",stdin);    freopen("calfflac.out","w",stdout);    string str="";    while(getline(cin,str))    {        s+='\n';        s+=str;    }    int l=s.length();    a[0].c='$';    a[1].c='#';    int len=2;    int ans=0,m=0;    for(int i=0;i<l;i++)    {        if(s[i]>='a'&&s[i]<='z')        {            a[len].c=s[i];            a[len++].n=i;            a[len++].c='#';        }        else if(s[i]>='A'&&s[i]<='Z')        {            a[len].c=s[i]-'A'+'a';            a[len++].n=i;            a[len++].c='#';        }    }    int id=0,mx=0;    for(int i=0;i<len;i++)    {        if(mx>i)            p[i]=min(mx-i,p[2*id-i]);        else p[i]=1;        while(a[i-p[i]].c==a[i+p[i]].c)            p[i]++;        if(i+p[i]>mx)        {            mx=i+p[i];            id=i;        }        if(ans<p[i])        {            ans=p[i];            m=i;        }    }    int ss,e,cnt=0;    e=a[m+p[m]-2].n;    ss=a[m-p[m]+2].n;    cout<<ans-1<<endl;    for(int i=ss;i<=e;i++)     {         if(s[i]=='\n')            cout<<endl;         else         cout<<s[i];     }     cout<<endl;}


这题数据不大所以只比别的代码快一点
Executing...
   Test 1: TEST OK [0.000 secs, 4652 KB]
   Test 2: TEST OK [0.000 secs, 4652 KB]
   Test 3: TEST OK [0.000 secs, 4652 KB]
   Test 4: TEST OK [0.000 secs, 4652 KB]
   Test 5: TEST OK [0.000 secs, 4652 KB]
   Test 6: TEST OK [0.000 secs, 4652 KB]
   Test 7: TEST OK [0.000 secs, 4652 KB]
   Test 8: TEST OK [0.000 secs, 4652 KB]

0 0