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. int s = 0, e = 0;
  25. int ans = 0;
  26. unordered_map<int,int> mp;
  27.  
  28.  
  29. while(e<n){
  30. //* Calculate state
  31. mp[str[e]]++;
  32.  
  33. if(mp.size() <= k){
  34. //* Valid Wndow => Compute Result && expand
  35. ans = max(ans, (e-s+1));
  36. e++;
  37. }
  38. else{
  39. //* Invalid window => Keep Shrink Window
  40. while(s<=e && mp.size() > k){
  41. mp[str[s]]--;
  42. if(mp[str[s]] == 0) mp.erase(str[s]);
  43. s++;
  44. }
  45.  
  46. //* Valid window => Compute Result && expand
  47. ans = max(ans, (e-s+1));
  48. e++;
  49. }
  50. }
  51.  
  52. cout << ans << endl;
  53. }
  54.  
  55.  
  56.  
  57.  
  58.  
  59.  
  60.  
  61. //* Template2 for Atmost k (i.e. <= k )
  62. //* (based on Cache Invalidation)
  63.  
  64. void consistency2(string str, int k){
  65. int n = str.size();
  66.  
  67.  
  68. unordered_map<int,int> mp;
  69. int s=0, e=0;
  70. int ans = 0;
  71.  
  72. while(e<n){
  73.  
  74. //* Calculate state
  75. mp[str[e]]++;
  76.  
  77. //* Invalid window => Shrink
  78. while(s<=e && mp.size()>k){
  79. mp[str[s]]--;
  80. if(mp[str[s]]==0) mp.erase(str[s]);
  81. s++;
  82. }
  83.  
  84. //* Valid window guranteed => Compute Result
  85. ans = max(ans, (e-s+1));
  86.  
  87. e++;
  88. }
  89.  
  90. cout << ans << endl;
  91.  
  92. }
  93.  
  94.  
  95.  
  96.  
  97.  
  98. void solve() {
  99.  
  100. int k;
  101. cin >> k;
  102. string str;
  103. cin >> str;
  104.  
  105. consistency1(str, k);
  106. consistency2(str, k);
  107.  
  108. }
  109.  
  110.  
  111.  
  112.  
  113.  
  114. int32_t main() {
  115. ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  116.  
  117. int t = 1;
  118. cin >> t;
  119. while (t--) {
  120. solve();
  121. }
  122.  
  123. return 0;
  124. }
Success #stdin #stdout 0.01s 5280KB
stdin
2
2
aababbcaacc
3
abcddefg
stdout
6
6
4
4