#include #ifdef LOCAL #include #else #define debug(...) void(0) #endif struct RollingHash { static inline uint64_t generate_base() { std::mt19937_64 mt(std::chrono::steady_clock::now().time_since_epoch().count()); std::uniform_int_distribution rand(2, RollingHash::mod - 1); return rand(mt); } RollingHash(uint64_t base = generate_base()) : base(base), power{1} {} template std::vector build(const T& s) const { int n = s.size(); std::vector hash(n + 1); hash[0] = 0; for (int i = 0; i < n; i++) hash[i + 1] = add(mul(hash[i], base), s[i]); return hash; } template uint64_t get(const T& s) const { uint64_t res = 0; for (const auto& x : s) res = add(mul(res, base), x); return res; } uint64_t query(const std::vector& hash, int l, int r) { assert(0 <= l && l <= r); extend(r - l); return add(hash[r], mod - mul(hash[l], power[r - l])); } uint64_t combine(uint64_t h1, uint64_t h2, size_t h2_len) { extend(h2_len); return add(mul(h1, power[h2_len]), h2); } int lcp(const std::vector& a, int l1, int r1, const std::vector& b, int l2, int r2) { int len = std::min(r1 - l1, r2 - l2); int lb = 0, ub = len + 1; while (ub - lb > 1) { int mid = (lb + ub) >> 1; (query(a, l1, l1 + mid) == query(b, l2, l2 + mid) ? lb : ub) = mid; } return lb; } private: static constexpr uint64_t mod = (1ULL << 61) - 1; const uint64_t base; std::vector power; static inline uint64_t add(uint64_t a, uint64_t b) { if ((a += b) >= mod) a -= mod; return a; } static inline uint64_t mul(uint64_t a, uint64_t b) { __uint128_t c = (__uint128_t)a * b; return add(c >> 61, c & mod); } inline void extend(size_t len) { if (power.size() > len) return; size_t pre = power.size(); power.resize(len + 1); for (size_t i = pre - 1; i < len; i++) power[i + 1] = mul(power[i], base); } }; using namespace std; typedef long long ll; #define all(x) begin(x), end(x) constexpr int INF = (1 << 30) - 1; constexpr long long IINF = (1LL << 60) - 1; constexpr int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1}; template istream& operator>>(istream& is, vector& v) { for (auto& x : v) is >> x; return is; } template ostream& operator<<(ostream& os, const vector& v) { auto sep = ""; for (const auto& x : v) os << exchange(sep, " ") << x; return os; } template bool chmin(T& x, U&& y) { return y < x and (x = forward(y), true); } template bool chmax(T& x, U&& y) { return x < y and (x = forward(y), true); } template void mkuni(vector& v) { sort(begin(v), end(v)); v.erase(unique(begin(v), end(v)), end(v)); } template int lwb(const vector& v, const T& x) { return lower_bound(begin(v), end(v), x) - begin(v); } void solve() { int N; string S; cin >> N >> S; RollingHash rh; auto hash = rh.build(S); int ans = 0; for (int i = 1; i < N; i++) { int len = rh.lcp(hash, 0, i, hash, i, N); if (len < i and len < N - i) ans += (S[len] < S[i + len]); else if (len == i and len < N - i) ans++; } cout << ans << '\n'; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int T; cin >> T; for (; T--;) solve(); return 0; }