New Distinct Substrings(后缀数组)

给定一个字符串,求不相同的子串的个数。\(n<=50005\)。

显然,任何一个子串一定是后缀上的前缀。先(按套路)把后缀排好序,对于当前的后缀\(S_i\),显然他有\(n-sa[i]\)个前缀。其中,有\(height[i]\)个前缀字符串在编号比它小的后缀中出现过,因此它对答案的贡献是\(n-sa[i]-height[i]\)。

#include <cstdio>
#include <cstring>
using namespace std; const int maxn=50005;
int T, n, m=maxn;
char s[maxn]; bool cmp(int *r, int a, int b, int j){
return r[a]==r[b]&&r[a+j]==r[b+j]; }
int *x, *y, *t, wa[maxn], wb[maxn], ws[maxn], sa[maxn], wv[maxn], ht[maxn];
void Suffixsort(char *r){
int i, j, p=0; x=wa, y=wb; m=maxn;
for (i=0; i<m; ++i) ws[i]=0;
for (i=0; i<n; ++i) ++ws[x[i]=r[i]];
for (i=1; i<m; ++i) ws[i]+=ws[i-1];
for (i=0; i<n; ++i) sa[--ws[r[i]]]=i;
for (j=1; p<n&&j<n; j<<=1, m=p+1){
for (p=0, i=n-j; i<n; ++i) y[p++]=i;
for (i=0; i<n; ++i) if (sa[i]>=j) y[p++]=sa[i]-j;
for (i=0; i<n; ++i) wv[i]=x[y[i]];
for (i=0; i<m; ++i) ws[i]=0;
for (i=0; i<n; ++i) ++ws[x[i]];
for (i=1; i<m; ++i) ws[i]+=ws[i-1];
for (i=n-1; i>0; --i) sa[--ws[wv[i]]]=y[i]; //这句话依然是背下来的
t=x; x=y; y=t; x[sa[0]]=1;
for (p=1, i=1; i<n; ++i)
x[sa[i]]=cmp(y, sa[i-1], sa[i], j)?p:++p; //+1
}
memset(ht, 0, sizeof(ht));
for (int i=0; i<n; ++i) --x[i]; p=0;
for (int i=0; i<n; ht[x[i++]]=p){
if (!x[i]) continue;
for (p?p--:0, j=sa[x[i]-1]; r[i+p]==r[j+p]&&i+p<n; ++p);
} ht[0]=0;
return;
} int main(){
scanf("%d", &T); int ans;
while (T--) {
scanf("%s", s); n=strlen(s);
Suffixsort(s); ans=0;
//for (int i=0; i<n; ++i) printf("%d ", sa[i]); puts("");
//for (int i=1; i<n; ++i) printf("%d ", ht[i]);
for (int i=0; i<n; ++i)
ans+=n-sa[i]-ht[i];
printf("%d\n", ans);
}
return 0;
}

最新文章

  1. JQuery 滚动轮播
  2. Lambda 表达式[MSDN]
  3. C#调用C和C++函数的一点区别
  4. POJ1837 Balance[分组背包]
  5. 一条命令使win7可以直接运行.net3.5程序
  6. 简单的TCPIP 客户端 服务器
  7. MongoDB - MongoDB CRUD Operations, Query Documents, Project Fields to Return from Query
  8. Newtonsoft.Json.JsonWriter
  9. WordPress FunCaptcha插件跨站脚本漏洞
  10. 数组在C++和java中的区别
  11. MySQL定时备份之使用Linux下的crontab定时备份实例
  12. C语言第二次博客作业---分支结构 陈张鑫
  13. 《javascript经典入门》-day01
  14. g4e基础篇#5 创建分支和保存代码
  15. XCode 设置自定义环境变量
  16. 20155321 《信息安全系统设计》课堂测试(ch06)
  17. QtGUI Module&#39;s Classes
  18. zoj 2588 Burning Bridges(割边/桥)
  19. BeanUtils介绍及其使用
  20. oracle 创建表并添加注释

热门文章

  1. Java-API:javax.servlet.http.HttpServletResponse
  2. yum 使用笔记
  3. 第 十五 课 Go 语言范围(Range)
  4. java基础知识(15)----StringBuffer与StringBuilder
  5. 12-18Windows窗体应用小程序之记事本(1)
  6. js将数组中一个或多个字段相同的子元素中合并
  7. tomcat跑多个项目和不同端口访问项目
  8. eclipse DDMS导出文件失败--android Failed to push the item
  9. 5-EasyNetQ之Publish(黄亮翻译)
  10. php中使用array_reduce给数组降维