码迷,mamicode.com
首页 > 其他好文 > 详细

POJ1509 Glass Beads 【后缀自动机】

时间:2018-01-17 00:34:00      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:ret   string   ems   strlen   log   code   max   for   puts   

题目大意

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

题解

建立后缀自动机,从根开始走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;
}

POJ1509 Glass Beads 【后缀自动机】

标签:ret   string   ems   strlen   log   code   max   for   puts   

原文地址:https://www.cnblogs.com/Mychael/p/8298100.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!