标签:end 输出 后缀 += i+1 数组 blog 个数 style
题意:
给定一个字符串S,找到另外一个字符串T,T既是S的前缀,也是S的后缀,并且在中间某个地方也出现一次,并且这三次出现不重合。求T最长的长度。
#include <iostream> #include <cstring> #include <vector> using namespace std; const int maxn = 1e6 + 100; char S[maxn]; int Next[maxn], extend[maxn]; vector<int> G[maxn]; int len; int c[maxn*4]; void Modify(int x, int s){ for(; x <= len; x += x&(-x)) c[x] += s; } int Query(int y){ if(y <= 0) return 0; int ans = 0; for(int x = y; x; x -= x&(-x)) ans += c[x]; return ans; } int query(int x, int y) { return x <= y ? Query(y) - Query(x-1) : 0; } void GetNext(char *T, int *Next){ int len = strlen(T); Next[0] = len; int a, p; for(int i = 1, j = -1; i < len; i++, j--){ if(j < 0 || i + Next[i-a] >= p){ if(j < 0) p = i, j = 0; while(p < len && T[p] == T[j]) p++, j++; Next[i] = j; a = i; } else Next[i] = Next[i-a]; } } void GetExtend(char *S, char *T, int *extend, int *Next){ GetNext(T, Next); int a, p; int slen = strlen(S), tlen = strlen(T); for(int i = 0, j = -1; i < slen; i++, j--){ if(j < 0 || i + Next[i-a] >= p){ if(j < 0) p = i, j = 0; while(p < slen && j < tlen && S[p] == T[j]) p++, j++; extend[i] = j; a = i; } else extend[i] = Next[i-a]; } } int main() { cin>>S; len = strlen(S); GetNext(S, Next); //for(int i = 0; i < len; i++) cout<<Next[i]<<" "; cout<<endl; for(int i = 0; i < len; i++) G[Next[i]].push_back(i); int ans = 0; for(int i = len-1; i >= 1; i--){ for(auto x : G[i]) Modify(x+1, 1); int n = G[i].size(); if(n == 0) continue; if(G[i][n-1] != len-i) continue; if(query(i+1, len-2*i+1)) { ans = i; break; } } cout<<ans<<endl; return 0; }
标签:end 输出 后缀 += i+1 数组 blog 个数 style
原文地址:http://www.cnblogs.com/Saurus/p/7637635.html