Menu Home

BZOJ 1692: Best Cow Line [USACO 2007 Dec]

Problem Description: 

FJ is about to take his N (1 <= N <= 30,000) cows to the annual
“Farmer of the Year” competition. In this contest every farmer
arranges his cows in a line and herds them past the judges.

The contest organizers adopted a new registration scheme this year:
simply register the initial letter of every cow in the order they
will appear (e.g., If FJ takes Bessie, Sylvia, and Dora in that
order, he just registers BSD). After the registration phase ends,
every group is judged in increasing lexicographic order (i.e.,
alphabetical order) according to the string of the initials of the
cows’ names.

FJ is very busy this year and has to hurry back to his farm, so he
wants to be judged as early as possible. He decides to rearrange
his cows, who have already lined up, before registering them.

FJ marks a location for a new line of the competing cows. He then
proceeds to marshal the cows from the old line to the new one by
repeatedly sending either the first or last cow in the (remainder
of the) original line to the end of the new line. When he’s finished,
FJ takes his cows for registration in this new order.

Given the initial order of his cows, determine the least lexicographic
string of initials he can make this way.



* Line 1: A single integer: N

* Lines 2..N+1: Line i+1 contains a single initial (‘A’..’Z’) of the
cow in the ith position in the original line




FJ has 6 cows in this order: ACDBCB


The least lexicographic string he can make. Every line (except perhaps
the last one) contains the initials of 80 cows (‘A’..’Z’) in the new

SAMPLE OUTPUT (file bclgold.out):



Step Original    New
#1    ACDBCB
#2    CDBCB      A
#3    CDBC        AB
#4    CDB          ABC
#5    CD             ABCB
#6    D               ABCBC
#7                      ABCBCD

This is a greedy problem. At a first thought, we can simply choose the smaller, lexicographically, letter at every operation. However, if the first and the last letters are the same, we have to know which will lead to a better solution. For a prefix length L and a suffix with the same length, we can compare the reverse of the prefix and the suffix then choose the smaller one. We can do this by using suffix array. We concatenate a symbol character and the reversed original string after the original string. The suffix array of this one has a special characteristic. For a string ABCD, the transformed string is ABCD#DCBA. If we calculate the rank array, we use it to quickly compare the prefix and the suffix.

#include <iostream>
#include <cstring>
#include <string>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <stdio.h>
#include <fstream>
#include <cmath>
#include <stdlib.h>
#include <iomanip>
#include <algorithm>
#include <limits.h>
#include <stack>
using namespace std;
#define FAST_IO ios::sync_with_stdio(false);
typedef pair<int,int> pii;
typedef pair<long long,long long> pll;
typedef pair<double,double> pdd;
typedef long long ll;
const int maxn = 1e6 + 10;
int T,K,wa[maxn],wb[maxn],wss[maxn],wv[maxn],s[maxn],sa[maxn],rnk[maxn],height[maxn];
bool cmp(int *r,int a,int b,int l){
    return r[a] == r[b] && r[a + l] == r[b + l];
void build(int *r,int *sa,int n,int m){
    int i,j,p,*x = wa,*y = wb;
    for(i = 0; i < m; i++) wss[i] = 0;
    for(i = 0; i < n; i++) wss[x[i] = r[i]]++;
    for(i = 1; i < m; i++) wss[i] += wss[i - 1];
    for(i = n - 1; i >= 0; i--) sa[--wss[x[i]]] = i;
    for(j = 1,p = 1; p < n; m = p, j *= 2){
        for(i = n - j,p = 0; i < n; i++) y[p++] = i;
        for(i = 0; i < n; i++) if(sa[i] >= j) y[p++] = sa[i] - j;
        for(i = 0; i < m; i++) wss[i] = 0;
        for(i = 0; i < n; i++) wv[i] = x[y[i]];
        for(i = 0; i < n; i++) wss[wv[i]]++;
        for(i = 1; i < m; i++) wss[i] += wss[i - 1];
        for(i = n - 1; i >= 0; i--) sa[--wss[wv[i]]] = y[i];
        for(p = 1,i = 1,x[sa[0]] = 0; i < n; i++){
            x[sa[i]] = cmp(y,sa[i - 1],sa[i],j) ? p - 1: p++;
void get_height(int n){
    int i,j,k = 0;
    for(i = 1; i <= n; i++) rnk[sa[i]] = i;
    for(i = 0; i < n; height[rnk[i++]] = k){
        for(k ? k-- : 0, j = sa[rnk[i] - 1]; s[k + i] == s[k + j]; k++);

int main(){
    string str;
    int sz = str.size();
    string tmp = str;
    str = str + "#" + tmp;
    int m = 0;
    for(int i = 0; i < str.size(); i++){
        s[i] = str[i];
        m = max(m,s[i] + 1);
    int n = str.size();
    build(s,sa,n + 1,m);
    int A = 0, B = sz + 1;
    string ans;
    while(A + B - sz - 1 < sz){
        if(rnk[A] < rnk[B]) {
            ans += str[A++];
        else ans += str[B++];
    return 0;


Categories: OI BZOJ String Problem Suffix Arrary


Leave a Reply

Your email address will not be published. Required fields are marked *