计蒜客链接~~~
给出一个只含数字的字符串,求出字符串中所有本质不同的字符串所表示的十进制数的和
先对字符串建一颗回文树,每个节点就代表了一个本质不同的回文串,遍历一遍树的所有节点,直接通过10进制hash得到回文区间的字符串的值
#include
using namespace std;
typedef long long LL;
const int base = 10;
const int mod = 1e9+7;
const int maxn = 2e6+26;
LL Hash[maxn],Pow[maxn];
void gethash(char *s,int len){
Pow[0] = 1LL;
for(int i = 1;i <= len; ++i){
Pow[i] = Pow[i-1]*10%mod;
Hash[i] = (Hash[i-1]*base+(LL)(s[i]-'0'))%mod;
}
}
LL getval(int l,int r){
return (Hash[r] - Hash[l-1]*Pow[r-l+1]%mod + mod)%mod;
}
struct PalindromicTree{
int last,tot,n,s[maxn],len[maxn],cnt[maxn],fail[maxn],tr[maxn][10];
int newnode(int Len){
for(int i = 0;i < 10; ++i) tr[tot][i] = 0;
len[tot] = Len;
cnt[tot] = 0;
return tot++;
}
void init(){
last = tot = n = 0;
newnode(0),newnode(-1);
fail[0] = 1; s[0] = -1;
}
int getfail(int x){
while(s[n-len[x]-1] != s[n]) x = fail[x];
return x;
}
void add(int x,int pos){
s[++n] = x;
int cur = getfail(last);
if(!tr[cur][x]){
int now = newnode(len[cur]+2);
fail[now] = tr[getfail(fail[cur])][x];
tr[cur][x] = now;
cnt[now] = pos; //记录下回文串的结尾位置
}
last = tr[cur][x];
}
}T;
char ss[maxn];
int main(){
scanf("%s",ss+1);
int len = strlen(ss+1);
T.init();
for(int i = 1;i <= len; ++i) T.add(ss[i]-'0',i);
LL res = 0LL;
gethash(ss,len);
for(int i = 2;i < T.tot; ++i)
res = (res+getval(T.cnt[i]-T.len[i]+1,T.cnt[i]))%mod;
printf("%lld",res);
return 0;
}