|
| 1 | +<snippet> |
| 2 | + <content><![CDATA[ |
| 3 | + // Suffix Array and LCP Array |
| 4 | + // suffix-array starts |
| 5 | + struct node{ |
| 6 | + int sortindex[2]; |
| 7 | + int index; |
| 8 | + }; |
| 9 | + int n,step; |
| 10 | + map<int,int> smap; |
| 11 | + vector<int> sarr; //suffix-array |
| 12 | + vector< vector<int> > rem(20); |
| 13 | + bool cmp( node& a, node& b) |
| 14 | + { |
| 15 | + return a.sortindex[0] == b.sortindex[0] ? ( a.sortindex[1] < b.sortindex[1] ? 1 : 0 ) : ( a.sortindex[0] < b.sortindex[0] ? 1 : 0 ) ; |
| 16 | + } |
| 17 | +
|
| 18 | + void suffix(string s) //call suffix(string) |
| 19 | + { |
| 20 | + n = s.length(); |
| 21 | + sarr.reserve(n); |
| 22 | + for (int i = 0; i < 20; i++) |
| 23 | + { |
| 24 | + rem[i].reserve(n); |
| 25 | + } |
| 26 | +
|
| 27 | + node sa[n]; |
| 28 | + step=1; |
| 29 | + int count=1; |
| 30 | + for( int i = 0; i < n; i++) |
| 31 | + { |
| 32 | + rem[0][i] = s[i] - 'a'; |
| 33 | + } |
| 34 | +
|
| 35 | + for( ; count>>1 < n ; step++,count<<=1 ) |
| 36 | + { |
| 37 | + for(int i=0 ; i<n ; i++) |
| 38 | + { |
| 39 | + sa[i].sortindex[0] = rem[step-1][i]; |
| 40 | + sa[i].sortindex[1] = i+count < n ? rem[step-1][i+count] : -1; |
| 41 | + sa[i].index = i; |
| 42 | + } |
| 43 | + sort(sa, sa+n, cmp); |
| 44 | + for(int i=0; i<n; i++) |
| 45 | + { |
| 46 | + rem[step][sa[i].index] = (i>0 && sa[i-1].sortindex[0]==sa[i].sortindex[0] && sa[i-1].sortindex[1]==sa[i].sortindex[1]) ? rem[step][sa[i-1].index] : i; |
| 47 | + } |
| 48 | + } |
| 49 | +
|
| 50 | + for (int i = 0; i < n; i++) { |
| 51 | + smap[rem[step-1][i]]=i; |
| 52 | + } |
| 53 | +
|
| 54 | + int j=0; |
| 55 | + for(auto& i : smap){ |
| 56 | + sarr[j++] = i.second; |
| 57 | + } |
| 58 | +
|
| 59 | + } |
| 60 | +
|
| 61 | +
|
| 62 | + int lcp(int x, int y) //length of lcp of suffixes starting at x and y |
| 63 | + { |
| 64 | + int k, ans=0; // lcp(x,y) = min[lcp(x,x+1),lcp(x+1,x+2),lcp(x+2,x+3),....,lcp(y-1,y)] |
| 65 | +
|
| 66 | + if (x==y) { // so, use rmq if there are too many queries |
| 67 | + return n-x; |
| 68 | + } |
| 69 | +
|
| 70 | + for(k=step-1; k>=0 && x<n && y<n; k--) |
| 71 | + { |
| 72 | + if (rem[k][x] == rem[k][y]) { |
| 73 | + x += 1<<k; |
| 74 | + y += 1<<k; |
| 75 | + ans+= 1<<k; |
| 76 | + } |
| 77 | + } |
| 78 | +
|
| 79 | + return ans; |
| 80 | + } |
| 81 | + //suffix array ends |
| 82 | +]]></content> |
| 83 | + <!-- Optional: Set a tabTrigger to define how to trigger the snippet --> |
| 84 | + <tabTrigger>suffix-array</tabTrigger> |
| 85 | + <!-- Optional: Set a scope to limit where the snippet will trigger --> |
| 86 | + <!-- <scope>source.python</scope> --> |
| 87 | +</snippet> |
0 commit comments