#include #include using namespace std; using namespace numbers; // z[i]: largest prefix(suffix if Reverse) starting(ending if Reverse) at i that is also a proper prefix(suffix if Reverse) // O(n) template vector z_function(vector s){ if(Reverse) reverse(s.begin(), s.end()); int n = (int)s.size(); vector z(n); for(auto i = 1, j = 0; i < n; ++ i){ if(i < j + z[j]) z[i] = min(j + z[j] - i, z[i - j]); while(i + z[i] < n && s[z[i]] == s[i + z[i]]) ++ z[i]; if(i + z[i] > j + z[j]) j = i; } if(Reverse) reverse(z.begin(), z.end()); return z; } int main(){ cin.tie(0)->sync_with_stdio(0); cin.exceptions(ios::badbit | ios::failbit); auto __solve_tc = [&](auto __tc_num)->int{ int n; string s; cin >> n >> s; auto z = z_function(vector(s.begin(), s.end())); int res = 0; for(auto i = 1; i < n; ++ i){ int len = min(z[i], i); res += n - i != len && (i == len || s[len] < s[i + len]); } cout << res << "\n"; return 0; }; int __tc_cnt; cin >> __tc_cnt; for(auto __tc_num = 0; __tc_num < __tc_cnt; ++ __tc_num){ __solve_tc(__tc_num); } return 0; } /* */ //////////////////////////////////////////////////////////////////////////////////////// // // // Coded by Aeren // // // ////////////////////////////////////////////////////////////////////////////////////////