Problem:
Score : 500 points

Problem Statement

Given is a string S of length N.

Find the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping.

More formally, find the maximum positive integer len such that there exist integers l_1 and l_2 ( 1 \leq l_1, l_2 \leq N - len + 1 ) that satisfy the following:

l_1 + len \leq l_2

S[l_1+i] = S[l_2+i] (i = 0, 1, ..., len - 1)

If there is no such integer len, print 0.

Constraints

2 \leq N \leq 5 \times 10^3

|S| = N

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping. If there is no such non-empty string, print 0 instead.

Sample Input 1

5
ababa

Sample Output 1

2

The strings satisfying the conditions are: a, b, ab, and ba. The maximum length among them is 2, which is the answer.
Note that aba occurs twice in S as contiguous substrings, but there is no pair of integers l_1 and l_2 mentioned in the statement such that l_1 + len \leq l_2.

Sample Input 2

2
xy

Sample Output 2

0

No non-empty string satisfies the conditions.

Sample Input 3

13
strangeorange

Sample Output 3

5

Solution in Rust (1.42.0) (judge verdict: Accepted)

#![allow(unused_imports)]
#![allow(non_snake_case)]
use std::cmp::*;
use std::collections::*;
use std::io::Write;

#[allow(unused_macros)]
macro_rules! debug {
    ($($e:expr),*) => {
        #[cfg(debug_assertions)]
        $({
            let (e, mut err) = (stringify!($e), std::io::stderr());
            writeln!(err, "{} = {:?}", e, $e).unwrap()
        })*
    };
}

fn main() {
    let n = read::<usize>();
    let s = read::<String>();
    let sa = construct_sa(&s);

    let (lcp, rank) = construct_lcp(&s, &sa);
    let st = SparseTable::new(&lcp);

    let mut ans = 0;
    for i in 0..n {
        for j in i + 1..n {
            let l = st.rmq(min(rank[i], rank[j]), max(rank[i], rank[j]));
            ans = max(ans, min(l, j - i));
        }
    }
    println!("{}", ans);
}

fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>()
        .split_whitespace()
        .map(|e| e.parse().ok().unwrap())
        .collect()
}

fn compare_sa(i: usize, j: usize, k: usize, n: usize, rank: &Vec<i32>) -> bool {
    if rank[i] != rank[j] {
        return rank[i] < rank[j];
    }
    let ri = if i + k <= n { rank[i + k] } else { -1 };
    let rj = if i + k <= n { rank[j + k] } else { -1 };
    ri < rj
}

fn construct_sa(s: &str) -> Vec<usize> {
    let n = s.len();
    let s = s.chars().collect::<Vec<_>>();
    let mut sa = vec![0; n + 1];

    let mut rank = vec![0; n + 1];
    for i in 0..n + 1 {
        sa[i] = i;
        rank[i] = if i < n { s[i] as u64 as i32 } else { -1 };
    }

    let mut k: usize = 1;
    while k <= n {
        let mut tmp = vec![0; n + 1];
        sa.sort_by_key(|&i| (rank[i], *rank.get(i + k).unwrap_or(&-1)));
        tmp[sa[0]] = 0;
        for i in 1..n + 1 {
            tmp[sa[i]] = tmp[sa[i - 1]];
            if compare_sa(sa[i - 1], sa[i], k, n, &rank) {
                tmp[sa[i]] += 1;
            }
        }
        rank = tmp;
        k *= 2;
    }
    sa
}

fn construct_lcp(s: &str, sa: &[usize]) -> (Vec<usize>, Vec<usize>) {
    let s = s.chars().collect::<Vec<_>>();
    let mut rank = vec![0; s.len() + 1];
    for i in 0..s.len() + 1 {
        rank[sa[i]] = i;
    }

    let mut h = 0;
    let mut lcp = vec![0; s.len() + 1];
    for i in 0..s.len() {
        let mut j = sa[rank[i] - 1];
        if h > 0 {
            h -= 1;
        }
        while j + h < s.len() && i + h < s.len() {
            if s[i + h] != s[j + h] {
                break;
            }
            h += 1;
        }

        lcp[rank[i] - 1] = h;
    }
    (lcp, rank)
}

struct SparseTable {
    st: Vec<Vec<usize>>,
    lookup: Vec<usize>,
}

impl SparseTable {
    fn new(v: &Vec<usize>) -> SparseTable {
        let mut b = 0;
        while (1 << b) <= v.len() {
            b += 1;
        }
        let mut st = vec![vec![0; 1 << b]; b];
        for i in 0..v.len() {
            st[0][i] = v[i];
        }
        for i in 1..b {
            let mut j = 0;
            while j + (1 << i) <= (1 << b) {
                st[i][j] = std::cmp::min(st[i - 1][j], st[i - 1][j + (1 << (i - 1))]);
                j += 1;
            }
        }
        let mut lookup = vec![0; v.len() + 1];
        for i in 2..lookup.len() {
            lookup[i] = lookup[i >> 1] + 1;
        }
        SparseTable {
            st: st,
            lookup: lookup,
        }
    }
    // [l, r)
    fn rmq(&self, l: usize, r: usize) -> usize {
        let b = self.lookup[r - l];
        std::cmp::min(self.st[b][l], self.st[b][r - (1 << b)])
    }
}