POJ1509 Glass Beads 【后缀自动机】

题目大意

找一个环串的起点,使得从其开始遍历字典序最小

题解

建立后缀自动机,从根开始走length步,走到的点就是这个最小串的结尾,其step即表示它在串中的位置
step - n + 1即为开始位置

#include<iostream>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define LL long long int
#define REP(i,n) for (int i = 1; i <= (n); i++)
#define Redge(u) for (int k = h[u],to; k; k = ed[k].nxt)
#define BUG(s,n) for (int i = 1; i <= (n); i++) cout<<s[i]<<' '; puts("");
#define cls(x) memset(x,0,sizeof(x))
using namespace std;
const int maxn = 40005,maxm = 100005,INF = 1000000000;
inline int read(){
    int out = 0,flag = 1; char c = getchar();
    while (c < 48 || c > 57) {if (c == '-') flag = -1; c = getchar();}
    while (c >= 48 && c <= 57) {out = (out << 3) + (out << 1) + c - '0'; c = getchar();}
    return out * flag;
}
int pre[maxn],step[maxn],ch[maxn][26],cnt,last,n;
char s[maxn];
void ins(int x){
    int p = last,np = ++cnt; cls(ch[np]);
    last = np; step[np] = step[p] + 1;
    while (p && !ch[p][x]) ch[p][x] = np,p = pre[p];
    if (!p) pre[np] = 1;
    else {
        int q = ch[p][x];
        if (step[q] == step[p] + 1) pre[np] = q;
        else {
            int nq = ++cnt; step[nq] = step[p] + 1;
            for (int i = 0; i < 26; i++) ch[nq][i] = ch[q][i];
            pre[nq] = pre[q]; pre[np] = pre[q] = nq;
            while (ch[p][x] == q) ch[p][x] = nq,p = pre[p];
        }
    }
}
void solve(){
    int u = 1;
    REP(i,n) for (int j = 0; j < 26; j++)
        if (ch[u][j]){u = ch[u][j]; break;}
    printf("%d\n",step[u] - n + 1);
}
int main(){
    int T = read();
    while (T--){
        scanf("%s",s + 1);
        n = strlen(s + 1); last = cnt = 1;
        memset(ch[1],0,sizeof(ch[1]));
        REP(i,n) ins(s[i] - 'a');
        REP(i,n) ins(s[i] - 'a');
        solve();
    }
    return 0;
}

转载于:https://www.cnblogs.com/Mychael/p/8298100.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值