#include #include using namespace std; using namespace atcoder; //using mint = modint1000000007; //const int mod = 1000000007; //using mint = modint998244353; //const int mod = 998244353; //const int INF = 1e9; //const long long LINF = 1e18; #define rep(i, n) for (int i = 0; i < (n); ++i) #define rep2(i,l,r)for(int i=(l);i<(r);++i) #define rrep(i, n) for (int i = (n-1); i >= 0; --i) #define rrep2(i,l,r)for(int i=(r-1);i>=(l);--i) #define all(x) (x).begin(),(x).end() #define allR(x) (x).rbegin(),(x).rend() #define endl "\n" #define P pair template inline bool chmax(A & a, const B & b) { if (a < b) { a = b; return true; } return false; } template inline bool chmin(A & a, const B & b) { if (a > b) { a = b; return true; } return false; } int naive(string s) { int ret = 0; rep2(i, 1, s.size()) { string s0 = s.substr(0, i); string s1 = s.substr(i, s.size() - i); if (s0 < s1)ret++; } return ret; } int solve(string s) { auto z = z_algorithm(s); int ans = 0; rep2(i, 1, s.size()) { auto idx0 = z[i]; auto idx1 = z[i] + i; if (idx0 >= i) { ans++; } else if (idx1 == s.size()) { // nop; } else if (s[idx0] < s[idx1]) { ans++; } } return ans; } void test() { int x = 100000; rep(i, x) { int ci = i; string s; rep(j, 5) { s += 'a' + ci % 10; ci /= 10; } if (naive(s) != solve(s)) { cout << s << endl; cout << naive(s) << endl; cout << solve(s) << endl; } } } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int t; cin >> t; while (t--) { int n; cin >> n; string s; cin >> s; cout << solve(s) << endl; } return 0; }