C - Alphabetic Removals
You are given a string
s consisting of n lowercase Latin letters. Polycarp wants to remove exactly k characters (k≤n≤n) from the string s. Polycarp uses the following algorithm k times:- if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;
- if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;
- ...
- remove the leftmost occurrence of the letter 'z' and stop the algorithm.
This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly k times, thus removing exactly k characters.
Help Polycarp find the resulting string.
InputThe first line of input contains two integers n and k (1≤k≤n≤4⋅105) — the length of the string and the number of letters Polycarp will remove.
The second line contains the string s consisting of n lowercase Latin letters.
OutputPrint the string that will be obtained from s after Polycarp removes exactly kkletters using the above algorithm k times.
If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
Examples15 3 cccaabababaccbc
cccbbabaccbc
15 9 cccaabababaccbc
cccccc
1 1 u
这个题就是给你一个已知长度的字符串,给你一个数k,要求要从这里面删去k个字符,删去的这k个字符要求是从a开始删除,如果a没有删完,那么就不能删除b,依次进行,直到删完k个字符就可以了。
#include <bits/stdc++.h>
using namespace std;
char s[400005];
int a[1000]; // a用来标记每个字母出现的次数
int main()
{
int n, k;
while(~scanf("%d %d",&n, &k))
{
getchar();
memset(a, 0,sizeof(a));
for(int i = 0; i < n; i ++)
{
scanf("%c",&s[i]);
a[s[i]] ++;
}
if(k >= n) printf("
"); //如果需要删除的k大于n,就全部删除没了
else
{
int num = 0;
for(int i = 97; ; i ++) // 从a开始删除,如果满足k>=a[i],把所有的字符都删去即可
{
if(k >= a[i])
{
num ++;
k = k - a[i];
}
else break;
}
for(int i = 0; i < n; i ++)
{
if(s[i] < 97 + num); //删除掉的不再输出
else
{
if(s[i] == 97 + num) // 没有全部删除完成,继续删除这个字符
{
if(k > 0)k--;
else printf("%c",s[i]);
}
else printf("%c",s[i]); // 输出不需要删除的
}
}
printf("
");
}
}
return 0;
}
发现可以省去好多代码:
#include <bits/stdc++.h>
using namespace std;
int n,m;
char str[400005];
int main()
{
cin>>n>>m;
cin>>str;
for(int i=0;i<=25;i++){
for(int j=0;j<n&&m;j++){
if(str[j] == 'a' + i){
str[j] = '0';
m--;
}
}
}
for(int i=0;i<n;i++){
if(str[i] != '0')cout<<str[i];
}
return 0;
}