dsu greedy strings *1500

Please click on ads to support us..

Python Code:

from collections import defaultdict
import sys
input = sys.stdin.readline

def inp():
    return(int(input()))
def inlt():
    return(list(map(int,input().split())))
def insr():
    s = input()
    return(list(s[:len(s) - 1]))
def invr():
    return(map(int,input().split()))
def compress(root, x):
    if root[x] == x:
        return x
    
    root[x] = compress(root, root[x])
    return root[x]
t = inp()
for _ in range(t):
    n, k = inlt()
    _dict = defaultdict(list)
    s = input()
    if s[-1] == '\n':
        s = s[:len(s) - 1]
    s = list(s)
    root = [i for i in range(26)]
    index = 0
        while k > 0 and index < len(s):
        ch = s[index]
        idx = ord(ch) - ord('a')
        compress(root, idx)
        
                if root[idx] > 0:
            root[idx] = idx - 1
                        s[index] = chr(root[idx] + ord('a'))
            k -= 1
        else:
            index += 1
    ans = ''
    for ch in s:
        idx = ord(ch) - ord('a')
        changed = compress(root, idx)
        ans += chr(changed + ord('a'))
    print(ans)
        
    

C++ Code:

#include<bits/stdc++.h>
using namespace std;
int n,k;
string s;
void solve()
{
	cin>>n>>k>>s;
	int now=0,tw=-1,m;
	for(int i=0;i<n;i++)
	{
		if(s[i]-'a'<=k) 
		{
			now=max(now,s[i]-'a');
			s[i]='a';
		}
		else 
		{
			if(tw==-1)
			{
				tw=s[i]-'a';
				m=s[i]-(k-now)-'a';
			}
			k=now;
			if(s[i]-'a'<=tw && s[i]-'a'>=m)
			{
				s[i]='a'+m;
			}
		}
	}
	cout<<s<<endl;
}
signed main()
{
    int _=1;
    cin>>_;
    while(_--)
    {
    	solve();
    }
}


Comments

Submit
0 Comments
More Questions

1725D - Deducing Sortability
1501A - Alexey and Train
721B - Passwords
1263D - Secret Passwords
1371B - Magical Calendar
1726E - Almost Perfect
1360C - Similar Pairs
900A - Find Extra One
1093D - Beautiful Graph
748A - Santa Claus and a Place in a Class
1511B - GCD Length
676B - Pyramid of Glasses
597A - Divisibility
1632A - ABC
1619D - New Year's Problem
242B - Big Segment
938A - Word Correction
159C - String Manipulation 10
258A - Little Elephant and Bits
1536C - Diluc and Kaeya
1428C - ABBB
1557A - Ezzat and Two Subsequences
255A - Greg's Workout
1059A - Cashier
1389C - Good String
1561A - Simply Strange Sort
1337B - Kana and Dragon Quest game
137C - History
1443C - The Delivery Dilemma
6C - Alice Bob and Chocolate