Advertisement
yicongli

LG4248

Mar 7th, 2019
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.22 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. #define gc c=getchar()
  6. #define r(x) read(x)
  7. #define ll long long
  8.  
  9. template<typename T>
  10. inline void read(T&x){
  11.     x=0;T k=1;char gc;
  12.     while(!isdigit(c)){if(c=='-')k=-1;gc;}
  13.     while(isdigit(c)){x=x*10+c-'0';gc;}x*=k;
  14. }
  15.  
  16. const int N=1e6+7;
  17.  
  18. int len[N];
  19. int to[N][26];
  20. int fa[N];
  21. int siz[N];
  22.  
  23. int tot;
  24.  
  25. inline int NewNode(int l,int *tr,int su){
  26.     ++tot;
  27.     len[tot]=l;
  28.     if(tr!=NULL)memcpy(to[tot],tr,26<<2);
  29.     fa[tot]=su;
  30.     return tot;
  31. }
  32.  
  33. inline int insert(int u,int c){
  34.     int t=NewNode(len[u]+1,NULL,0);
  35.     for(;u&&!to[u][c];u=fa[u])to[u][c]=t;
  36.     if(!u){
  37.         fa[t]=1;
  38.         return t;
  39.     }
  40.     int v=to[u][c];
  41.     if(len[v]==len[u]+1){
  42.         fa[t]=v;
  43.         return t;
  44.     }
  45.     int x=NewNode(len[u]+1,to[v],fa[v]);
  46.     fa[t]=fa[v]=x;
  47.     for(;u&&to[u][c]==v;u=fa[u])to[u][c]=x;
  48.     return t;
  49. }
  50.  
  51. int ord[N];
  52. int cnt[N];
  53. char s[N];
  54.  
  55. int main(){
  56.     scanf("%s",s);
  57.     int n=strlen(s);
  58.     int lst=NewNode(0,NULL,0);
  59.     for(int i=0;i<n;++i){
  60.         siz[lst=insert(lst,s[i]-'a')]=1;
  61.     }
  62.     ll ans=(ll)n*(n-1)*(n+1)/2;
  63.     for(int i=1;i<=tot;++i)cnt[len[i]]++;
  64.     for(int i=1;i<=n;++i)cnt[i]+=cnt[i-1];
  65.     for(int i=1;i<=tot;++i)ord[cnt[len[i]]--]=i;
  66.     for(int i=tot;i;--i){
  67.         int x=ord[i];
  68.         ans-=(ll)siz[fa[x]]*siz[x]*len[fa[x]]*2;
  69.         siz[fa[x]]+=siz[x];
  70.     }
  71.     printf("%lld\n",ans);
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement