【2019徐州网络赛 G】Colorful String(PAM)

The value of a string s is equal to the number of different letters which appear in this string.

Your task is to calculate the total value of all the palindrome substring.

Input
The input consists of a single string |s| ( 1 ≤ ∣ s ∣ ≤ 3 × 1 0 5 ) (1 \le |s| \le 3 \times 10^5) (1s3×105)

The string ss only contains lowercase letters.

Output
Output an integer that denotes the answer.

样例输入
abac
样例输出
6
代码:

#include
#include
#include
#include
#define maxx 300005
#define N 26
using namespace std;
typedef long long ll;
ll ans=0;
struct PAM
{
    int nex[maxx][N];

    int res[maxx];
    int fail[maxx];
    int cnt[maxx];
    int num[maxx];
    int len[maxx];
    int S[maxx];
    int last;
    int n;
    int p;

    inline int newNode(int l)//if single case
    {
        //for(int i=0;i<26;i++)nex[p][i]=0;
        //cnt[p]=0;
        //num[p]=0;
        len[p]=l;
        return p++;
    }
    void init()
    {

        p=0;
        newNode(0);newNode(-1);
        last=0;n=0;
        S[n]=-1;
        fail[0]=1;
    }
    inline int getFail(int x)
    {
        while(S[n-len[x]-1]!=S[n])x=fail[x];
        return x;
    }
    inline void insert(int c)
    {
        c-='a';
        S[++n]=c;
        int cur=getFail(last);
        if(!nex[cur][c])
        {
            int now=newNode(len[cur]+2);

            fail[now]=nex[getFail(fail[cur])][c];
            nex[cur][c]=now;
            num[now]=num[fail[now]]+1;

        }
        last=nex[cur][c];
        //cout<
        ans+=res[last];
        cnt[last]++;

    }
    void count()
    {
        for(int i=p;i>=0;i--)cnt[fail[i]]+=cnt[i];
    }
    int vis[26];
    void dfs(int now,int def)
    {
        for(int i=0;i<26;i++)
        {
            int k=def;
            if(nex[now][i])
            {
                if(vis[i]==0)k++;
                vis[i]++;
                ans+=(ll)k*cnt[nex[now][i]];
                dfs(nex[now][i],k);
                vis[i]--;
            }
        }
    }
}pam;
char c[maxx];
int main()
{
    scanf("%s",c);
    pam.init();
    for(int i=0;c[i];i++)
        pam.insert(c[i]); 
    pam.count();
    pam.dfs(0,0);
    pam.dfs(1,0);
    cout<<ans<<endl;
    return 0;
}

你可能感兴趣的:(PAM)