codeforces 1038a(找最长的前k个字母出现相同次数的字符串)

codeforces 1038a

You are given a string s of length n, which consists only of the first
k letters of the Latin alphabet. All letters in string s are
uppercase.

A subsequence of string s is a string that can be derived from s by
deleting some of its symbols without changing the order of the
remaining symbols. For example, “ADE” and “BD” are subsequences of
“ABCDE”, but “DEA” is not.

A subsequence of s called good if the number of occurences of each of
the first k letters of the alphabet is the same.

Find the length of the longest good subsequence of s.

Input The first line of the input contains integers n (1≤n≤1e5) and k
(1≤k≤26)

The second line of the input contains the string s of length n. String
s only contains uppercase letters from ‘A’ to the k-th letter of Latin
alphabet.

Output Print the only integer — the length of the longest good
subsequence of string s.

Examples 
input 
9 3 
ACAABCCAB 
output 
6 
input 
9 4 
ABCABCABC 
output 
0 

思路如下

  1. 先判断前 k 个字母是不是都有。
  2. 如果都有,找前k 个字母中 出现次数最少的那个字母,那么这个最少次数 * k ,就是答案,同桶排去统计字母出现的次数
  3. 如果前 k 个字母没有全部出现在所给的字符串中,直接输出 0

题解如下

#include<iostream>
#include<algorithm>
using namespace std;
int barrel[100];

int main()
{
    //freopen("test.txt","r",stdin);
    int n,k;
    scanf("%d %d ", &n,&k);
    char ch;
    for(int i = 0; i < n; i ++)
    {
        scanf("%c",&ch);
        barrel[ch] ++;
    }
    int ans = 1e9;
    for(int i = 'A'; i <= 64 + k; i ++)
    {
        ans = min(ans , barrel[i]);
    }
    printf("%d",ans * k);

    return 0;
}
发布了84 篇原创文章 · 获赞 120 · 访问量 8646

猜你喜欢

转载自blog.csdn.net/qq_34261446/article/details/104094163