LuoGu P1368 工艺
最小表示法的板子题.这个题可以用(n:log_2:n)的(SA)求最小表示法也可以用更加优秀的(O(n))的(two:pointers.)
(SA)不讲,因为会(SA)的人应该都能一眼看出来怎么做.主要讲(two:pointers)求出最小表示法.
具体思想是先把字符串加倍,然后用两个指针,它们的初始位置相差(1).
我们就以两个指针为起始点用另一个指针从前向后比较,,每次我们遇到不相同的,假设是(i)指针较大,当前比较到了(i+k).
就可以得知从(i)到(i+k)之内所有的最小表示法都是不如(j)开头的优的.于是我们直接跳过这一段.就可以了.
(Code:)
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <string>
#include <vector>
#include <queue>
#include <cmath>
#include <ctime>
#include <map>
#include <set>
#define MEM(x,y) memset ( x , y , sizeof ( x ) )
#define rep(i,a,b) for (int i = a ; i <= b ; ++ i)
#define per(i,a,b) for (int i = a ; i >= b ; -- i)
#define pii pair < int , int >
#define X first
#define Y second
#define rint read<int>
#define int long long
#define pb push_back
using std::set ;
using std::pair ;
using std::max ;
using std::min ;
using std::priority_queue ;
using std::vector ;
using std::swap ;
using std::sort ;
using std::unique ;
using std::greater ;
template < class T >
inline T read () {
T x = 0 , f = 1 ; char ch = getchar () ;
while ( ch < '0' || ch > '9' ) {
if ( ch == '-' ) f = - 1 ;
ch = getchar () ;
}
while ( ch >= '0' && ch <= '9' ) {
x = ( x << 3 ) + ( x << 1 ) + ( ch - 48 ) ;
ch = getchar () ;
}
return f * x ;
}
const int N = 3e5 + 100 ;
int n , v[N<<1] ;
signed main (int argc , char * argv[]) {
n = rint () ; rep ( i , 1 , n ) v[i] = rint () ;
rep ( i , 1 , n ) v[i+n] = v[i] ;
int i = 1 , j = 2 , k ;
while ( i <= n && j <= n ) {
for (k = 0 ; k <= n && v[i+k] == v[j+k] ; ++ k) ;
if ( k == n ) break ;
if ( v[i+k] > v[j+k] ) {
i = i + k + 1 ;
if ( i == j ) ++ i ;
} else {
j = j + k + 1 ;
if ( i == j ) ++ j ;
}
}
int pos = min ( i , j ) ;
rep ( w , pos , pos + n - 1 ) printf ("%lld " , v[w] ) ;
system ("pause") ; return 0 ;
}