计蒜客 2018南京网络赛 I Skr(回文树)

题目:给一串由0..9组成的数字字符串,求所有不同回文串的权值和。比如说“1121”这个串中有“1”,“2”,“11”,“121”三种回文串,他们的权值分别是1,2,11,121。最终输出ans=135。

思路:之前写了马拉车的算法,网上看到的这个题是回文树的模板题。。。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN=2000000+10;
const ll mod=1e9+7;
const int N = 10 ;
ll qmod(ll x,ll p)
{
    ll ans=1;
    while(p)
    {
        if(p&1) ans=ans*x%mod;
        x=x*x%mod;
        p>>=1;
    }
    return ans;
}
struct Palindromic_Tree {
    int next[MAXN][N] ;
    int fail[MAXN] ;
    int cnt[MAXN] ;
    int num[MAXN] ;
    int len[MAXN] ;
    int S[MAXN] ;
    int last ;
    int n ;
    int p ;
    ll sum[MAXN];

    int newnode ( int l ) {
        for ( int i = 0 ; i < N ; ++ i ) next[p][i] = 0 ;
        cnt[p] = 0 ;
        num[p] = 0 ;
        sum[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 ;
    }

    int get_fail ( int x ) {
        while ( S[n - len[x] - 1] != S[n] ) x = fail[x] ;
        return x ;
    }

    void add ( int c ) {
        c -= '0' ;
        S[++ n] = c ;
        int cur = get_fail ( last ) ;
        if ( !next[cur][c] ) {
            int now = newnode ( len[cur] + 2 ) ;
            fail[now] = next[get_fail ( fail[cur] )][c] ;
            next[cur][c] = now ;
            num[now] = num[fail[now]] + 1 ;

            sum[now] = ((sum[cur]*10ll)%mod + c)%mod;
            if(len[cur]>=0)
                sum[now] = (sum[now] + (c*qmod(10,len[cur]+1))%mod)%mod;

        }
        last = next[cur][c] ;
        cnt[last] ++ ;
    }

    ll Sum () {
        ll ans=0;
        for ( int i = p - 1 ; i >= 0 ; -- i )
            (ans += sum[i])%=mod;
        return ans;
    }
}pam;

char s[MAXN];
int main()
{
    scanf("%s",s+1);
    int l=strlen(s+1);
    pam.init();
    for(int i=1;i<=l;i++)
        pam.add(s[i]);
    printf("%lld\n",pam.Sum());
    return 0;
}

猜你喜欢

转载自blog.csdn.net/dllpXFire/article/details/82623117