int n, m, k, q; voidwork() { string s; cin >> n; cin >> s; vector<int> vec; vec.reserve(n); for (int i = 0; i < n; i++) { while (!vec.empty() && s[i] > s[*(vec.rbegin())]) vec.pop_back(); if (vec.empty() || s[i] <= s[*(vec.rbegin())]) vec.push_back(i); } int m = vec.size(), ans = m; for (int i = 1; i < m; i++) if (s[vec[i]] == s[vec[i - 1]]) ans--; else break; for (int i = 0; i < m / 2; i++) swap(s[vec[i]], s[vec[m - i - 1]]); if (is_sorted(s.begin(), s.end())) cout << ans - 1 << endl; else cout << -1 << endl; } intmain() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin >> t; while (t --> 0) { work(); } }
int n, m, k; pll q[N * 3]; int a[N]; int minn[N]; voidwork() { cin >> n; for (int i = 1; i <= n; i++) cin >> a[i]; minn[n + 1] = n; ll sum = 0, ans = 0; for (int i = n; i >= 1; i--) minn[i] = min(minn[i + 1], a[i]); int l = N, r = N; for (int i = 1; i <= n; i++) { sum += minn[i + 1]; q[r++] = {minn[i + 1], 1}; } ans = sum; for (int i = 1; i < n; i++) { int now = a[i], pos = r - 1; sum -= q[l].first; if (--q[l].second == 0) l++; ll cnt = 0; while (pos >= l && q[pos].first >= now) { sum -= q[pos].first * q[pos].second; sum += now * q[pos].second; cnt += q[pos].second; r--, pos--; } q[r++] = {now, cnt}; q[r++] = {n, 1}; sum += n; ans = max(ans, sum); } cout << ans << endl; } intmain() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t; cin >> t; while (t --> 0) { work(); } }