fork(1) download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. string solve(string &s,int n, int k){
  4. bool processed[26];
  5. memset(processed, false, sizeof(processed));
  6. vector<int>indicesFor[26];
  7. for(int i=0;i<n;i++)indicesFor[s[i]-'a'].push_back(i);
  8.  
  9. for(int i=0;i<n;i++){
  10. if(k<=0)break;
  11. if(s[i]=='a')continue; // just for the shake of optimization (not needed though)
  12.  
  13. int delta = min(k, s[i]-'a');
  14. char hi = s[i];
  15. char lo = s[i]-delta;
  16.  
  17. for(int j=hi-'a';j>lo-'a';j--){
  18. if(processed[j])break;
  19. for(auto idx:indicesFor[j])s[idx]=lo;
  20. processed[j]=true;
  21. }
  22.  
  23. k-=delta;
  24. // break;
  25. }
  26.  
  27. return s;
  28. }
  29. int main() {
  30. int t;
  31. cin>>t;
  32. while(t--){
  33. int n,k;
  34. string s;
  35. cin>>n>>k>>s;
  36. cout<<solve(s,n,k)<<"\n";
  37. }
  38. }
Success #stdin #stdout 0.01s 5460KB
stdin
1
4 19
ekyv
stdout
aatt