Poj--3376(扩展KMP,Trie)
2014-12-18 00:22:30
思路:这题目好想不好做- -、(事实上能想到就不容易了)
看了题解的思路....然后自己敲的。
考虑:把所有正串都加进一棵Trie,然后用每个串的逆串去跑Trie,此时会出现两种情况:
(1)匹配完成,那么就说明存在一个正串的前缀是这个逆串。如果剩余的逆串回文,那么能形成回文。
(2)匹配失败,Trie未结束,说明不能构成回文。
(3)Trie已经跑到叶子节点,匹配未结束,那么如果正串剩余部分回文,那么能形成回文。
用扩展KMP处理出一个串的每个后缀是不是回文串,方法是用该串和其逆串仅用扩展KMP匹配,如果ex[i]=(从i到末尾的长度),那么说明从i到末尾的后缀是回文的。
1 #include <cstdio> 2 #include <cstring> 3 #include <cstdlib> 4 #include <cmath> 5 #include <vector> 6 #include <map> 7 #include <set> 8 #include <stack> 9 #include <queue> 10 #include <iostream> 11 #include <algorithm> 12 using namespace std; 13 #define lp (p << 1) 14 #define rp (p << 1|1) 15 #define getmid(l,r) (l + (r - l) / 2) 16 #define MP(a,b) make_pair(a,b) 17 typedef long long ll; 18 typedef unsigned long long ull; 19 const int INF = 1 << 30; 20 const int maxn = 2000010; 21 22 int n,tot,tcnt; 23 int ex[maxn],next[maxn],len[maxn]; 24 char tmp[maxn],S[maxn],rtmp[maxn]; 25 ll ans; 26 struct Trie{ 27 int v; 28 int flag; 29 Trie *next[26]; 30 }*root; 31 32 Trie t[maxn]; 33 34 void Ex_kmp(char *s,char *rs,int m){ 35 int j,k = 0,p,L; 36 next[0] = m; 37 while(k < m - 1 && rs[k + 1] == rs[k]) k++; 38 next[1] = k; 39 k = 1; //因为1位置已经算过 40 for(int i = 2; i < m; ++i){ 41 p = k + next[k] - 1,L = next[i - k]; 42 if(i + L <= p) next[i] = L; else{ 43 j = (p - i + 1 > 0 ? p - i + 1 : 0); 44 while(i + j < m && rs[i + j] == rs[j]) j++; 45 next[k = i] = j; 46 } 47 } 48 k = 0; 49 while(k < m && rs[k] == s[k]) k++; 50 ex[0] = k; 51 k = 0; //因为0位置已经算过 52 for(int i = 1; i < m; ++i){ 53 p = k + ex[k] - 1,L = next[i - k]; 54 if(i + L <= p) ex[i] = L; else{ 55 j = (p - i + 1 > 0 ? p - i + 1 : 0); 56 while(i + j < m && s[i + j] == rs[j]) j++; 57 ex[k = i] = j; 58 } 59 } 60 } 61 62 void Insert_Trie(char *s,int m){ 63 Trie *p = root,*q; 64 for(int i = 0; i < m; ++i){ 65 int id = s[i] - 'a'; 66 if(p -> next[id] == NULL){ 67 q = &t[tcnt++]; 68 for(int i = 0; i < 26; ++i) q -> next[i] = NULL; 69 q -> v = 0; 70 q -> flag = 0; 71 p -> next[id] = q; 72 } 73 p = p -> next[id]; 74 p -> v += (i + 1 < m && ex[i + 1] == m - i - 1) ? 1 : 0; 75 } 76 p -> flag++; 77 } 78 79 void Find(char *s,int m){ 80 Trie *p = root; 81 for(int i = 0; i < m; ++i){ 82 int id = s[i] - 'a'; 83 if(p -> next[id] == NULL) return; 84 p = p -> next[id]; 85 if(p -> flag && (i + 1 >= m || ex[i + 1] == m - i - 1)) ans += p -> flag; 86 } 87 ans += p -> v; 88 } 89 90 int main(){ 91 tcnt = tot = 0; 92 root = &t[tcnt++]; 93 for(int i = 0; i < 26; ++i) root -> next[i] = NULL; 94 scanf("%d",&n); 95 for(int i = 0; i < n; ++i){ 96 scanf("%d",len + i); 97 scanf("%s",S + tot); 98 for(int j = 0; j < len[i]; ++j) rtmp[j] = S[tot + len[i] - 1 - j]; 99 Ex_kmp(S + tot,rtmp,len[i]); 100 Insert_Trie(S + tot,len[i]); 101 tot += len[i]; 102 } 103 tot = 0; 104 ans = 0; 105 for(int i = 0; i < n; ++i){ 106 for(int j = 0; j < len[i]; ++j) rtmp[j] = S[tot + len[i] - 1 - j]; 107 Ex_kmp(rtmp,S + tot,len[i]); 108 Find(rtmp,len[i]); 109 tot += len[i]; 110 } 111 printf("%I64d\n",ans); 112 return 0; 113 }