# BZOJ1369/BZOJ2865 【后缀数组+线段树】

## Description

XX在进行字符串研究的时候，遇到了一个十分棘手的问题。

1、i≤K≤j。

2、子串T只在S中出现过一次。

## Sample Input

agoodcookcooksgoodfood

1
2
3
3
2
2
3
3
2
2
3
3
2
1
2
3
3
2
1
2
3
4

## HINT

N<=5*10^5

#include<bits/stdc++.h>

using namespace std;

typedef pair<int, int> pi;
const int N = 5e5 + 10;
const int INF_of_int = 1e9;

int typ1[N << 2], typ2[N << 2];

#define LD (t << 1)
#define RD (t << 1 | 1)

void build(int t, int l, int r) {
typ1[t] = INF_of_int;
typ2[t] = -INF_of_int;
if (l == r) return;
int mid = (l + r) >> 1;
build(LD, l, mid);
build(RD, mid + 1, r);
}

void modify(int t, int l, int r, int ql, int qr, int typ, int val) {
if (ql > qr) return;
if (ql <= l && r <= qr) {
if (typ == 1) {
typ1[t] = min(typ1[t], val);
} else {
typ2[t] = max(typ2[t], val);
}
return;
}
int mid = (l + r) >> 1;
if (qr <= mid) modify(LD, l, mid, ql, qr, typ, val);
else if (ql > mid) modify(RD, mid + 1, r, ql, qr, typ, val);
else {
modify(LD, l, mid, ql, mid, typ, val);
modify(RD, mid + 1, r, mid + 1, qr, typ, val);
}
}

void output(int t, int l, int r, int val, int pos) {
if (typ1[t]) val = min(val, typ1[t]);
if (typ2[t]) val = min(val, pos - typ2[t] + 1);
if (l == r) {
printf("%d\n", val);
return;
}
int mid = (l + r) >> 1;
if (pos <= mid) output(LD, l, mid, val, pos);
else output(RD, mid + 1, r, val, pos);
}

struct Suffix_Array {
int s[N], n, m;
int c[N], x[N], y[N];
int sa[N], rank[N], height[N];

void init(int len, char *c) {
n = len, m = 0;
for (int i = 1; i <= n; i++) {
s[i] = c[i];
m = max(m, s[i]);
}
}

for (int i = 1; i <= m; i++) c[i] = 0;
for (int i = 1; i <= n; i++) c[x[y[i]]]++;
for (int i = 1; i <= m; i++) c[i] += c[i - 1];
for (int i = n; i >= 1; i--) sa[c[x[y[i]]]--] = y[i];
}

void buildsa() {
for (int i = 1; i <= n; i++) x[i] = s[i], y[i] = i;
int now;
for (int k = 1; k <= n; k <<= 1) {
now = 0;
for (int i = n - k + 1; i <= n; i++) y[++now] = i;
for (int i = 1; i <= n; i++) if (sa[i] > k) y[++now] = sa[i] - k;
y[sa[1]] = now = 1;
for (int i = 2; i <= n; i++) y[sa[i]] = (x[sa[i]] == x[sa[i - 1]] && x[sa[i] + k] == x[sa[i - 1] + k]) ? now : ++now;
swap(x, y);
if (now == n) break;
m = now;
}
}

void buildrank() {
for (int i = 1; i <= n; i++) rank[sa[i]] = i;
}

void buildheight() {
for (int i = 1; i <= n; i++) {
int k = max(height[rank[i - 1]] - 1, 0);
for (; s[i + k] == s[sa[rank[i] - 1] + k]; k++);
height[rank[i]] = k;
}
}

void build(int len, char *c) {
init(len, c);
buildsa();
buildrank();
buildheight();
}

void solve() {
for (int i = 1; i <= n; i++) {
int len = max(height[rank[i]], height[rank[i] + 1]);
if (i + len > n) continue;
modify(1, 1, n, i, i + len, 1, len + 1);
modify(1, 1, n, i + len, n, 2, i);
}
}
} Sa;

int len;
char s[N];

int main() {
#ifdef dream_maker
freopen("input.txt", "r", stdin);
#endif
scanf("%s", s + 1);
len = strlen(s + 1);
Sa.build(len, s);
build(1, 1, len);
Sa.solve();
for (int i = 1; i <= len; i++) output(1, 1, len, len, i);
return 0;
}
posted @ 2018-12-05 16:46 Dream_maker_yk 阅读(...) 评论(...) 编辑 收藏