Solution -「SV 2020 Round I」SA
\(\mathcal{Description}\)
求出处 owo。
给定一个长度为 \(n\),仅包含小写字母的字符串 \(s\),问是否存在长度为 \(n\),仅包含小写字母的字符串 \(t\),使得 \(t<s\) 且 \(s,t\) 的后缀数组(\(\text{Suffix Array}\),sa[]
)相同。
\(n\le50\)。(建议开到 \(n\le2\times10^5\)。
\(\mathcal{Solution}\)
奇怪的结论
若存在 \(t\),则存在一个 \(t\),其与 \(s\) 仅相差一个字符。考试的时候我猜出来了 w!
算法
有了上面的结论就非常简单了。首先一个显而易见的特判:若 \(s\) 的字符集不是小写字母的一段前缀,显然存在 \(t\)。
然后,先求出原串的 sa[]
。尝试让某个 \(s_i\) 减小 \(1\)。显然,修改 \(s_i\) 不影响 sa[]
,需要保证 \(\operatorname{suffix(i)}\) 是以 \(s_i\) 开头的后缀中最小的。则满足条件的 \(s_i\) 仅有字符集大小个。暴力修改这些 \(s_i\),求出 sa2[]
与原来的 sa[]
比较即可。
复杂度 \(\mathcal O(|\mathit{\Sigma}|n\log n)\)。标算是暴力 sort
求 sa[]
,且尝试修改了所有的 \(s_i\),复杂度 \(\mathcal O(n^3\log n)\),并不优秀。
\(\mathcal{Code}\)
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#define YES() ( puts ( "Exists" ), exit ( 0 ) )
#define NO() ( puts ( "Does not exist" ), exit ( 0 ) )
const int MAXN = 50;
int n, sa[MAXN + 5];
char s[MAXN + 5];
inline void suffixSort ( int* sa ) {
int m = 'z', x[200] {}, y[200] {}, c[200] {};
for ( int i = 1; i <= n; ++ i ) c[i] = 0;
for ( int i = 1; i <= n; ++ i ) ++ c[x[i] = s[i]];
for ( int i = 1; i <= m; ++ i ) c[i] += c[i - 1];
for ( int i = n; i; -- i ) sa[c[x[i]] --] = i;
for ( int j = 1; j <= n; j <<= 1 ) {
int cnt = 0;
for ( int i = n - j + 1; i <= n; ++ i ) y[++ cnt] = i;
for ( int i = 1; i <= n; ++ i ) if ( sa[i] > j ) y[++ cnt] = sa[i] - j;
for ( int i = 1; i <= m; ++ i ) c[i] = 0;
for ( int i = 1; i <= n; ++ i ) ++ c[x[i]];
for ( int i = 1; i <= m; ++ i ) c[i] += c[i - 1];
for ( int i = n; i; -- i ) sa[c[x[y[i]]] --] = y[i], y[i] = 0;
std::swap ( x, y ), x[sa[1]] = 1, cnt = 1;
for ( int i = 2; i <= n; ++ i ) {
x[sa[i]] = cnt += y[sa[i]] ^ y[sa[i - 1]] || y[sa[i] + j] ^ y[sa[i - 1] + j];
}
if ( ( m = cnt ) == n ) break;
}
}
inline void precheck () {
bool used[26] {};
for ( int i = 1; i <= n; ++ i ) used[s[i] - 'a'] = true;
for ( int i = 0, ue = false; i < 26; ++ i ) {
if ( ue && used[i] ) YES ();
ue |= ! used[i];
}
}
inline void check () {
int nsa[MAXN + 5] {};
suffixSort ( nsa );
for ( int i = 1; i <= n; ++ i ) if ( nsa[i] ^ sa[i] ) return ;
YES ();
}
int main () {
freopen ( "sa.in", "r", stdin );
freopen ( "sa.out", "w", stdout );
scanf ( "%s", s + 1 ), n = strlen ( s + 1 );
precheck (), suffixSort ( sa );
for ( int i = 1, las = 'a', t; i <= n; ++ i ) {
if ( s[sa[i]] == las ) continue;
t = s[sa[i]], s[sa[i]] = las, check (), las = s[sa[i]] = t;
}
return NO (), 0;
}
```cpp