URAL 2040 Palindromes and Super Abilities 2 (Palindromic Tree)

题目大意:

对于输入的字符串s (长度不超过5000000, 只包含a, b两种字符) 如果这个字符串从左到右依次加入形成的s, 当每个字符加入时求新增加的本质不同的回文串的数量


大致思路:

和 URAL 1940 Palindromes and Super Abilities一样就是简单的Palindromic Tree的应用, 就是时间有些紧, 所以读入和输出需要一些优化


代码如下:

Result  :  Accepted     Memory  :  88406 KB     Time  :  0.14 s

/*
 * Author: Gatevin
 * Created Time:  2015/3/30 20:52:20
 * File Name: Rin_Tohsaka.cpp
 */
#include<iostream>
#include<sstream>
#include<fstream>
#include<vector>
#include<list>
#include<deque>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<bitset>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cctype>
#include<cmath>
#include<ctime>
#include<iomanip>
using namespace std;
const double eps(1e-8);
typedef long long lint;

#define maxn 5000010

char s[maxn];
char ans[maxn];
//string s, ans;
struct Palindromic_Tree
{
    struct node
    {
        int next[2];
        int len, sufflink;
    };
    node tree[maxn];
    int L, len, suff;
    void newnode()
    {
        L++;
        for(int i = 0; i < 2; i++)
            tree[L].next[i] = -1;
        tree[L].len = tree[L].sufflink;
        return;
    }
    void init()
    {
        L = 0, suff = 2;
        newnode(), newnode();
        tree[1].len = -1; tree[1].sufflink = 1;
        tree[2].len = 0, tree[2].sufflink = 1;
        return;
    }
    bool addLetter(int pos)
    {
        int cur = suff, curlen = 0;
        int alp = s[pos] - 'a';
        while(1)
        {
            curlen = tree[cur].len;
            if(pos - 1 - curlen >= 0 && s[pos - 1 - curlen] == s[pos])
                break;
            cur = tree[cur].sufflink;
        }
        if(tree[cur].next[alp] != -1)
        {
            suff = tree[cur].next[alp];
            return false;
        }
        newnode();
        suff = L;
        tree[L].len = tree[cur].len + 2;
        tree[cur].next[alp] = L;
        if(tree[L].len == 1)
        {
            tree[L].sufflink = 2;
            return true;
        }
        while(1)
        {
            cur = tree[cur].sufflink;
            curlen = tree[cur].len;
            if(pos - 1 - curlen >= 0 && s[pos - 1 - curlen] == s[pos])
            {
                tree[L].sufflink = tree[cur].next[alp];
                break;
            }
        }
        return true;
    }
};

Palindromic_Tree pal;

int main()
{
    ios_base::sync_with_stdio (false);//加上这句用cin, cout string 类型就不会TLE了
    /*
       cin>>s;
       int n = s.length();
       */
    /*
     * 另外我用scanf("%s", s); printf("%s", ans)也是TLE
     * 用puts和gets就没TLE了..
     */
    gets(s);
    int n = strlen(s);
    pal.init();
    for(int i = 0; i < n; i++)
        ans[i] = '0' + pal.addLetter(i);
    //cout<<ans;
    puts(ans);
    return 0;
}


你可能感兴趣的:(tree,Palindromic,2040,ural)