题目大意:
就是对于给出的字符串S, 长度不超过1000, 求其中本质不同的子串的数量, 这些子串满足在字符串S中出现了至少不重合的2次
大致思路:
如果将S建立后缀自动机的话, 记录每个节点处的串最早一次和最后一次出现的位置, 然后状态 t 处的字符串长度为[Min(t), Max(t)]比较其和rightmost - leftmost 的大小即可知道这个状态下有多少满足条件的串
时间复杂度O(n)
代码如下:
Result : Accepted Memory : 1904 KB Time : 15 ms
/*
* Author: Gatevin
* Created Time: 2015/5/4 23:07:10
* File Name: Rin_Tohsaka.cpp
*/
#include<iostream>
#include<sstream>
#include<fstream>
#include<vector>
#include<list>
#include<deque>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<bitset>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cctype>
#include<cmath>
#include<ctime>
#include<iomanip>
using namespace std;
const double eps(1e-8);
typedef long long lint;
#define foreach(e, x) for(__typeof(x.begin()) e = x.begin(); e != x.end(); ++e)
#define SHOW_MEMORY(x) cout<<sizeof(x)/(1024*1024.)<<"MB"<<endl
#define maxm 1010
#define maxn 2020
struct Suffix_Automation
{
struct State
{
State *par;
State *go[26];
int right, val, mi, leftmost, rightmost;
void init(int _val = 0)
{
par = 0, val = _val, right = 0, mi = 0, leftmost = 1e9, rightmost = -1;
memset(go, 0, sizeof(go));
}
};
State *last, *cur, *root;
State nodePool[maxn];
State* newState(int val = 0)
{
cur->init(val);
return cur++;
}
void init()
{
cur = nodePool;
root = newState();
last = root;
}
void extend(int w, int pos)
{
State *p = last;
State *np = newState(p->val + 1);
np->right = 1;
np->rightmost = np->leftmost = pos;
while(p && p->go[w] == 0)
{
p->go[w] = np;
p = p->par;
}
if(p == 0)
{
np->par = root;
}
else
{
State *q = p->go[w];
if(p->val + 1 == q->val)
{
np->par = q;
}
else
{
State *nq = newState(p->val + 1);
memcpy(nq->go, q->go, sizeof(q->go));
nq->par = q->par;
q->par = nq;
np->par = nq;
while(p && p->go[w] == q)
{
p->go[w] = nq;
p = p->par;
}
}
}
last = np;
}
int d[maxm];
State* b[maxn];
void topo()
{
int maxVal = 0;
int cnt = cur - nodePool;
memset(d, 0, sizeof(d));
for(int i = 1; i < cnt; i++)
maxVal = max(maxVal, nodePool[i].val), d[nodePool[i].val]++;
for(int i = 1; i <= maxVal; i++) d[i] += d[i - 1];
for(int i = 1; i < cnt; i++) b[d[nodePool[i].val]--] = &nodePool[i];
b[0] = root;
}
void SAMInfo()
{
int cnt = cur - nodePool;
State *p;
for(int i = cnt - 1; i > 0; i--)
{
p = b[i];
p->par->right += p->right;
p->mi = p->par->val + 1;
p->par->leftmost = min(p->par->leftmost, p->leftmost);
p->par->rightmost = max(p->par->rightmost, p->rightmost);
}
return;
}
};
Suffix_Automation sam;
char s[maxm];
int main()
{
while(scanf("%s", s) != EOF)
{
if(s[0] == '#') break;
int len = strlen(s);
sam.init();
for(int i = 0; i < len; i++)
sam.extend(s[i] - 'a', i);
sam.topo();
sam.SAMInfo();
int ans = 0;
int cnt = sam.cur - sam.nodePool;
for(int i = 1; i < cnt; i++)
if(sam.b[i]->right >= 2)
{
int tmp = sam.b[i]->rightmost - sam.b[i]->leftmost;
if(tmp >= sam.b[i]->val)
ans += sam.b[i]->val - sam.b[i]->mi + 1;
else if(tmp >= sam.b[i]->mi)
ans += tmp - sam.b[i]->mi + 1;
}
printf("%d\n", ans);
}
return 0;
}