Keep On Movin HDU

来源:互联网 发布:php 上传txt 编辑:程序博客网 时间:2024/05/29 10:40

  

 Keep On Movin

HDU - 5744

Professor Zhang has kinds of characters and the quantity of thei-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
(1n105) -- the number of kinds of characters. The second line contains n integers a1,a2,...,an(0ai104)
.
Output
For each test case, output an integer denoting the answer.
Sample Input
441 1 2 432 2 251 1 1 1 151 1 2 2 3
Sample Output
3613
思路:这道题是一道思维题,问求所有方案中最短回文串的最长的长度。如果所给的所有字符的数量都是偶数,即给出的n个数字都是偶数,那么这种情况最简单,因为偶数一定可以构成回文,所以长度就是所有加起来的和,重点就是如果含有奇数个的字符怎么办,想一想,如果存在奇数个的字符,那么它自己本身可以构成一个回文串,但是不可以在相加,因为两个奇数个数字符串肯定不能构成回文,两边一边一个肯定不能均分,但是奇数和偶数个数的字符串倒是可以,奇数的放在中间,偶数放在两边一边一个进行放置但是这样思路就很混乱,没法实现。
题目不是求最长的吗,为了思路统一可以把偶数全加起来,如果是奇数减一后变成偶数再加到总和中,这样出现一个奇数的就会单独多出一个串来,并且长度均为1,最后加完只需要,把这个偶数的和平均的分给每个奇数串就可以了,就可以使最短的回文串最长,即平均值
code:
#include <iostream>#include <cstdio>#include <cstring>using namespace std;int t;int sum,odd,n,k;int main(){    int i;    scanf("%d",&t);    while(t--){        sum = 0;        odd = 0;        scanf("%d",&n);        for(i = 1; i <= n; i++){            scanf("%d",&k);            if(k%2==0){                sum += k;            }            else{                sum += k-1;                odd++;            }        }        if(odd==0)printf("%d\n",sum);        else printf("%d\n",sum/2/odd*2+1);//这是最关键的一句,sum是总的偶数的个数sum/2就是能分成多少组去填充奇数字符串,每一个实际上代表左右两边整体        //sum/2/odd代表这用这些组去填充这些个奇数串每个奇数串可以得到多少组去填充,sum/2/odd*2就像刚才说的sum/2的时候实际上是一个整体,代表了两边,所以实际        //长度要乘2才是填充上的长度,最后加1就是加的原本字符串的那一个字符,最后就是总的长度    }    return 0;}