fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define int long long int
  4. #define double long double
  5.  
  6.  
  7. const int M = 1000000007;
  8. const int N = 3e5+9;
  9. const int INF = 2e9+1;
  10. const int MAXN = 100000;
  11. const int LINF = 2000000000000000001;
  12.  
  13. //_ ***************************** START Below *******************************
  14.  
  15.  
  16.  
  17.  
  18.  
  19. //* Template1 for Atmost k (i.e. <= k )
  20.  
  21. void consistency1(string str, int k){
  22. int n = str.size();
  23.  
  24. unordered_map<char,int> mp;
  25. int ans = 0;
  26.  
  27. int s = 0, e = 0;
  28. while(e<n){
  29. mp[str[e]]++;
  30.  
  31. if(mp.size() <= k){
  32. ans = max(ans, e-s+1);
  33. e++;
  34. }
  35. else{
  36. while(s<=e && mp.size() > k){
  37. mp[str[s]]--;
  38. if(mp[str[s]] == 0) mp.erase(str[s]);
  39. s++;
  40. }
  41. ans = max(ans, e-s+1);
  42. e++;
  43. }
  44. }
  45.  
  46. cout << ans << " ";
  47.  
  48. }
  49.  
  50.  
  51.  
  52.  
  53.  
  54.  
  55.  
  56. //* Template2 for Atmost k (i.e. <= k )
  57. //* (based on Cache Invalidation)
  58.  
  59. void consistency2(string str, int k){
  60. int n = str.size();
  61.  
  62. unordered_map<char,int> mp;
  63. int ans = 0;
  64.  
  65. int s = 0, e = 0;
  66. while(e<n){
  67. mp[str[e]]++;
  68.  
  69. while(s<=e && mp.size() > k){
  70. mp[str[s]]--;
  71. if(mp[str[s]] == 0) mp.erase(str[s]);
  72. s++;
  73. }
  74. ans = max(ans, e-s+1);
  75. e++;
  76. }
  77.  
  78. cout << ans << " ";
  79.  
  80.  
  81.  
  82. }
  83.  
  84.  
  85.  
  86.  
  87.  
  88. void solve() {
  89.  
  90. int k;
  91. cin >> k;
  92. string str;
  93. cin >> str;
  94.  
  95. consistency1(str, k);
  96. consistency2(str, k);
  97. cout << endl;
  98.  
  99. }
  100.  
  101.  
  102.  
  103.  
  104.  
  105. int32_t main() {
  106. ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  107.  
  108. int t = 1;
  109. cin >> t;
  110. while (t--) {
  111. solve();
  112. }
  113.  
  114. return 0;
  115. }
Success #stdin #stdout 0.01s 5292KB
stdin
2
2
aababbcaacc
3
abcddefg
stdout
6 6 
4 4