BOJ 480 田田背课文
2014-08-07 23:41
986 查看
题意:给出一个字符串,求出一个最短的只出现一次的子串的长度。
思路:利用后缀数组,我们能求得最长的重复子串。那该长度加一就是最短的只出现一次的子串的长度。
代码如下:
思路:利用后缀数组,我们能求得最长的重复子串。那该长度加一就是最短的只出现一次的子串的长度。
代码如下:
#include <cstdio> #include <cstring> #include <string> #include <iostream> using namespace std; const int MAX = 1000100; void radix(int * str, int *a, int *b, int n, int m){ static int count[MAX]; memset(count,0,sizeof(count)); for(int i = 0; i < n; ++i) ++count[str[a[i]]]; for(int i = 1; i <= m; ++i) count[i] += count[i-1]; for(int i = n -1; i >= 0; --i) b[--count[str[a[i]]]] = a[i]; } void suffix_array(int* str,int * sa, int n, int m) { static int rank[MAX],a[MAX],b[MAX]; for(int i = 0; i < n; ++i) rank[i] =i; radix(str,rank,sa,n,m); rank[sa[0]] = 0; for(int i = 1; i < n; ++i) rank[sa[i]]= rank[sa[i-1]] +(str[sa[i]]!=str[sa[i-1]]); for(int i = 0; 1<<i< n; ++i){ for(int j = 0; j < n; ++j){ a[j] = rank[j]+1; b[j] = j + (1<<i) >=n? 0: rank[j + (1<<i)] + 1; sa[j] = j; } radix(b,sa,rank,n,n); radix(a,rank,sa,n,n); rank[sa[0]] = 0; for(int j = 1; j < n; ++j){ rank[sa[j]] = rank[sa[j-1]] + (a[sa[j-1]] != a[sa[j]] || b[sa[j-1]] != b[sa[j]]); } } } int duplicate_substr(string str) { string rev; static int s[MAX],sa[MAX],rank[MAX],h[MAX]; int n = str.length(); copy(str.begin(),str.end(),s); suffix_array(s,sa,n,256); for(int i = 0 ; i < n; ++i) rank[sa[i]] = i; int k = 0; int ans1 =0,pos1 = 0; for(int i = 0; i < n; ++i){ k = k==0? 0: k - 1; while(rank[i] > 0 && s[i + k] == s[sa[rank[i] - 1] + k]) ++k; h[rank[i]] = k; if(h[rank[i]] > ans1){ ans1 = h[rank[i]]; pos1 = i; } } return str.substr(pos1,ans1).length(); } int main(void) { int T; string str; while(cin>>str){ cout<<duplicate_substr(str) + 1<<'\n'; } return 0; }
相关文章推荐
- 后缀数组模板-boj477.新来的小妹妹 & boj477. 田田背课文
- BOJ 438 田田的公司
- BOJ 451 田田的算术题
- boj 451 田田的算数题 区间更新树状数组
- 新标日语初级第25课应用课文默写
- 告诉大家如何下钻石vga,480*640的竖版壁纸
- 新版中日交流标准日本语初级第三课之应用课文
- 介绍一种wince 6.0 如何添加 640*480液晶驱动的好方法
- boj 1329 简单算法 利用栈来计数
- boj 1307 二叉树前序遍历
- iphone视图屏幕元素-像素大小 目前iphone,ipod touch 屏幕:320*480
- BOJ1499 合法食物链 floyd
- o.boj 1047 MODULO
- o.boj 1417 Cloudiris's Flower
- o.boj 1477 cloudiris的巧克力账本
- boj-311-小马过河
- BOJ 1003 Guess
- 准备 70-480 考试 - 配置学习环境
- [递归与分治算法][BOJ]1032-邮局选址问题
- BOJ 1577 Easy Game