D. Palindromes Coloring

https://codeforces.com/problemset/problem/1624/D

题意:给定一个长度为n的字符串s还有一数字k <= n,s只包含小写字母。现在需要将s中的字符分为k组回文串,可以使用任意数量的字符,求k组中最小的最大长度是多少。

思路:只选择一部分字符进行分组,而且要求回文,先求出相同字符对的数量tot。如果tot % k == 0,那么每组的长度都一样,再考虑奇数字符能否分配到每组中来使最终长度再增加1。如果tot % k != 0,说明有一组要比其他的组的字符对少一对,此时可以求出这组使用的字符对数量,然后再考虑没使用的字符对的数量与奇数字符的数量与k的关系,看能否为每组都添加一个最中心字符来使得长度 + 1.

总结:一开始没读懂题,考虑了奇数字符数量跟k的关系。。没注意到要可以只使用部分字符串。这个题目,应该想清楚分为k组,具体怎么分配,采取什么策略,所以深刻的理解问题才是重要的,认知要多提升啊。

inline void solve(){
    int n, k;
    cin >> n >> k;

    string s;
    cin >> s;

    array<int, 26> cnt = {};
    for(int i = 0; i < n; ++i) {
        cnt[s[i] - 'a'] ++;
    }

    int odd = 0;
    int tot = 0;
    for (int i = 0; i < 26; ++i) {
        odd += (cnt[i] & 1);
        tot += cnt[i];
    }
    tot -= odd;
    tot >>= 1;

    if (tot % k == 0) {
        cout << (tot / k * 2 + (odd >= k)) << '\n';
    }
    else {
        int num = tot / k;
        int rem = tot % k;
        cout << (num * 2 + (rem * 2 + odd >= k)) << '\n';
    }

}
posted @ 2025-03-14 10:17  _Yxc  阅读(16)  评论(0)    收藏  举报