贪心

    xiaoxiao2025-01-25  4

    Description

    Professor Zhang has kinds of characters and the quantity of the i-th character is ai. Professor Zhang wants to use all the characters build several palindromic strings. He also wants to maximize the length of the shortest palindromic string.

    For example, there are 4 kinds of characters denoted as 'a', 'b', 'c', 'd' and the quantity of each character is {2,3,2,2} . Professor Zhang can build {"acdbbbdca"}, {"abbba", "cddc"}, {"aca", "bbb", "dcd"}, or {"acdbdca", "bb"}. The first is the optimal solution where the length of the shortest palindromic string is 9.

    Note that a string is called palindromic if it can be read the same way in either direction.

    Input

    There are multiple test cases. The first line of input contains an integer T, indicating the number of test cases. For each test case:

    The first line contains an integer n (1≤n≤105) -- the number of kinds of characters. The second line contains n integers a1,a2,...,an (0≤ai≤104).

    Output

    For each test case, output an integer denoting the answer.

    Sample Input

    4 4 1 1 2 4 3 2 2 2 5 1 1 1 1 1 5 1 1 2 2 3

    Sample Output

    3 6 1 3

    题意:

    有n个字符,每个字符ai个,你需要构造一些字符串,使得这些字符串都是回文串,而且这些回文串恰好用完所有字符 而且最短的回文串最长,输出这个长度。

    分析:

    显然如果某个字符的个数为奇数,那么一定有剩余的一个该字符没有其他字符与之配对所以一定处于某个字符串的中间。所以字符个数为奇数的个数就是最终回文字符串的个数。特别的如果全是偶数,那么回文字符串的个数为1.那么将剩下的字符成对的放入所有回文字符串的两边。保证尽量平均即可。

    代码:

    #include <stdio.h> #include <string.h> #include <iostream> using namespace std; int a[100010]; int main() { std::cout.sync_with_stdio(false); int t; cin >> t; while(t--) { int n,cnt = 0,sum = 0; cin >> n; for(int i = 0 ; i < n ; i ++) cin >> a[i]; for(int i = 0 ; i < n ; i ++) { if(a[i]%2 == 1) { cnt ++; a[i]--; } sum += a[i]; } int ans; if(cnt == 0) { ans = sum; } else { sum /= 2; ans = sum/cnt * 2 + 1; } cout << ans << "\n"; } return 0; }

    转载请注明原文地址: https://ju.6miu.com/read-1295749.html
    最新回复(0)