题目描述:
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.
输入描述:
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).
输出描述:
For each test case, output an integer denoting the answer.
输入:
4
4
1 1 2 4
3
2 2 2
5
1 1 1 1 1
5
1 1 2 2 3
输出:
3
6
1
3
题意:
开始输入T,有T组测试样例,每组测试样例给定n个数,代表n个字符的个数,每个数代表的字符是唯一确定的,将这些字符组成若干个回文串(可以一个,也可以多个),找出所有组合方式中最短 回文串 的最长长度。
题解:
统计所有的字符中奇数的1的个数和偶数2的对数,比如一个字符有5个,则表示为2对偶数,1个奇数。
最后判断奇数和偶数的数量关系,如果奇数偶数都不为0,将偶数平均分配到奇数中,表示一个奇数对应这n对偶数,输出(偶数对数/奇数个数)*2+1。
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
const int maxn = 100000 + 5;
int a[maxn];
int main(){
int t,n;
scanf("%d",&t);
while(t--){
int ou = 0,ji = 0;
scanf("%d",&n);
for(int i = 0; i < n; i ++){
scanf("%d",&a[i]);
//cout<<a[i]<<endl;
if(a[i] % 2 == 1) ji ++;
ou += (a[i] / 2);
}
if(ji == 0 && ou == 0) printf("1\n");
else if(ji == 0 && ou != 0) printf("%d\n",ou * 2);
else{
int ans = (ou / ji) * 2 + 1;
printf("%d\n",ans);
}
}
return 0;
}