BZOJ2882: 工藝(字尾陣列)

自為風月馬前卒發表於2018-11-27

題意

題目連結

Sol

直接把序列複製一遍

字尾陣列即可

在前(N)個位置中取(rak)最小的輸出

#include<bits/stdc++.h>
using namespace std;
const int MAXN = 1e6 + 10;
inline int read() {
    char c = getchar(); int x = 0, f = 1;
    while(c < `0` || c > `9`) {if(c == `-`) f = -1; c = getchar();}
    while(c >= `0` && c <= `9`) x = x * 10 + c - `0`, c = getchar();
    return x * f;
}
int N, M, tax[MAXN], tp[MAXN], rak[MAXN], sa[MAXN], a[MAXN];
void Qsort() {
    for(int i = 0; i <= M; i++) tax[i] = 0;
    for(int i = 1; i <= N; i++) tax[rak[i]]++;
    for(int i = 1; i <= M; i++) tax[i] += tax[i - 1];
    for(int i = N; i >= 1; i--) sa[tax[rak[tp[i]]]--] = tp[i];
}
void SuffixSort() {
    for(int i = 1; i <= N; i++) tp[i] = i, rak[i] = a[i];
    Qsort();
    for(int w = 1, p; p < N; w <<= 1, M = p) {
        p = 0;
        for(int i = 1; i <= w; i++) tp[++p] = N - w + i;
        for(int i = 1; i <= N; i++) if(sa[i] > w) tp[++p] = sa[i] - w;
        Qsort(); swap(tp, rak);
        rak[sa[1]] = p = 1;
        for(int i = 2; i <= N; i++) rak[sa[i]] = (tp[sa[i]] == tp[sa[i - 1]] && tp[sa[i] + w] == tp[sa[i - 1] + w]) ? p : ++p; 
    }
}
int main() {
    M = N = read();
    for(int i = 1; i <= N; i++) a[i] = a[i + N] = read(); N <<= 1;  
    SuffixSort();
//  for(int i = 1; i <= N; i++) printf("%d ", rak[i]); 
    int mx; rak[mx = 0] = 1e9 + 10;
    for(int i = 1; i <= N / 2; i++) if(rak[i] < rak[mx]) mx = i; 
    for(int i = mx; i <= mx + N / 2 - 1; i++) printf("%d ", a[i]);
    return 0;
}
/*
4
2 2 1 2

10
10 9 8 7 1 6 5 4 3 2 

20
10 9 8 7 6 5 4 3 2 1 10 9 8 7 6 5 4 3 2 1
*/

相關文章