1. 程式人生 > >[字尾陣列 模板]

[字尾陣列 模板]

我是用 HDU-2594來測試的本模板
程式碼


#include <bits/stdc++.h>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <string>
#include <math.h>
#include <stack>
#include <vector>
#include <queue>
#include <set>
#include <map> using namespace std; #define rep(i, l, r) for(int i = l; i < r; i++) #define per(i, r, l) for(int i = r; i >= l; i--) #define dbgln(...) cerr<<"["<<#__VA_ARGS__":"<<(__VA_ARGS__)<<"]"<<"\n" #define dbg(...) cerr<<"["<<#__VA_ARGS__":"<<(__VA_ARGS__)<<"]"
typedef long long ll; typedef unsigned long long ull; typedef pair<int, int>pii; const int N = (int) 50000 * 3 + 10000; // 這裡不知道為啥 陣列必須開大好多才行,不然RE const int M = (int) 1e6 + 11; const int MOD = (int) 1e9 + 7; const int INF = (int) 0x3f3f3f3f; const ll INFF = (ll) 0x3f3f3f3f3f3f3f3f; /*-----------------------------------------------------------*/
int n, k; int Rank[N + 1], sa[N + 1], height[N + 1], tmp[N + 1]; int MIN[N + 1][40]; bool cmp_sa(int i, int j){ if(Rank[i] != Rank[j]) return Rank[i] < Rank[j]; else { int ri = i + k <= n ? Rank[i + k] : -1; int rj = j + k <= n ? Rank[j + k] : -1; return ri < rj; } } void SA(string s){ // 排名為 1 - n ,其他都是0 - (n - 1) // sa , 0 - (n - 1) n = s.size(); for(int i = 0; i <= n; i++){ sa[i] = i; Rank[i] = (i < n) ? s[i] : -1; } for(k = 1; k <= n; k <<= 1){ sort(sa, sa + n + 1, cmp_sa); tmp[sa[0]] = 0; for(int i = 1; i <= n; i++){ tmp[sa[i]] = tmp[sa[i - 1]] + (cmp_sa(sa[i - 1], sa[i]) ? 1 : 0); } for(int i = 0; i <= n; i++){ Rank[i] = tmp[i]; } } // height and rank for(int i = 0; i <= n; i++) Rank[sa[i]] = i; int h = 0; height[0] = 0; for(int i = 0; i < n; i++){ int j = sa[Rank[i] - 1]; if(h > 0) h--; for(;j + h < n && i + h < n; h++){ if(s[j + h] != s[i + h]) break; } height[Rank[i] - 1] = h; } // height[i] = sa[i]於sa[i + 1] 的lcp // RMQ for(int i = 1; i <= n; i++) MIN[i][0] = height[i]; for(int j = 1; (1 << j) <= n; j++){ for(int i = 1; i <= n; i++){ MIN[i][j] = min(MIN[i][j - 1], MIN[i + (1 << (j - 1))][j - 1]); } } } int LCP(int L, int R){ // 0 - (n - 1) L = Rank[L]; R = Rank[R]; if(L > R) swap(L, R); R--; int k = 0; while((1 << (k + 1)) <= R - L + 1) k++; // 2^k可以完全覆蓋 return min(MIN[L][k], MIN[R - (1 << k) + 1][k]); } int main(){ string a, b, s; while(cin >> a >> b){ s = ""; s += a; s += '$'; s += b; SA(s); //dbgln(s); /* for(int i = 0; i <= (int)s.size(); i++){ dbg(i); dbg(sa[i]); dbgln(Rank[i]); } */ bool flag = 0; for(int i = a.size() + 1; s[i]; i++){ if(LCP(0, i) == ((int)s.size() - i)){ for(int j = i; s[j]; j++){ printf("%c", s[j]); } printf(" %d\n", (int)s.size() - i); flag = 1; break; } } if(!flag) puts("0"); } return 0; }