1 solutions

  • 0
    @ 2026-6-20 14:07:45

    题目解析

    首先将所有能配对的字母配对,假设配成了 pp 对,然后剩下 odod 个单独的字符(即出现次数为奇数的字符)。

    如果 od=0od = 0,那么最优方案一定是将所有的字母拼成一个回文串,答案为 2p2p(即所有配对的总长度)。

    否则拼成 odod 个串,然后将这 pp 对字符均匀分配给这 odod 个串,每个串的长度为 2⌊p/od⌋+12\lfloor p / od \rfloor + 1。

    核心思路:

    • 统计每种字母出现次数,将偶数部分(除以 2)累计到 sum 中,同时统计有多少个出现次数为奇数的字母,记为 od。
    • 如果 od = 0,说明全部都是偶数次,可以拼成一个完整的回文串,答案为 sum * 2。
    • 如果 od > 0,则拼成 od 个回文串,将 sum 对字母均匀分配到 od 个串中,每个串长度为 sum / od * 2 + 1。

    时间复杂度:O(T×n)O(T \times n)。


    参考代码

    #include <bits/stdc++.h>
    #define rep(i, a, b) for (int i = (a); i <= (b); ++i)
    #define dep(i, a, b) for (int i = (a); i >= (b); --i)
    using namespace std;
    typedef long long ll;
    
    const int N = 2e5 + 20;
    
    inline int read() {
        char c = getchar();
        int x = 0, f = 1;
        while (c < '0' || c > '9') {
            if (c == '-') f = -1;
            c = getchar();
        }
        while (c >= '0' && c <= '9') {
            x = x * 10 + c - '0';
            c = getchar();
        }
        return x * f;
    }
    
    int q[N];
    int n;
    
    int main() {
        int T = read();
        while (T--) {
            n = read();
            int sum = 0;
            int od = 0;
            rep(i, 1, n) {
                q[i] = read();
                if (q[i] & 1) {
                    od++;
                    sum += q[i] / 2;
                }
                else
                    sum += q[i] / 2;
            }
            if (!od)
                printf("%d\n", sum * 2);
            else
                printf("%d\n", sum / od * 2 + 1);
        }
        return 0;
    }
    
    • 1

    Information

    ID
    190
    Time
    1000ms
    Memory
    128MiB
    Difficulty
    9
    Tags
    (None)
    # Submissions
    7
    Accepted
    7
    Uploaded By