题目描述:
Keep On Movin
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 525 Accepted Submission(s): 381
Problem 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
题意:给出不同字符的个数,将他们组成回文串,找出组成的回文串中最小串长度的最大值。
题解:若某一种字符的数目是偶数个,那么将其除以二得到能参与组成回文串的对数,若某一种字符的数目是奇数个,那么将这种字符单独成串,留下一个字符,将其他的偶数个字符与上面类似处理,累加这些可组成回文串的对数cnt,若不存在奇数串,则答案为cnt*2,若有cnt1个偶数串,则答案是1+(cnt/cnt1)*2.
ac代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=1e5+5;
int a[maxn];
int main()
{
//freopen("in.txt","r",stdin);
int cas;
scanf("%d",&cas);
while(cas--)
{
int n;
scanf("%d",&n);
int cnt1=0,cnt2=0;
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
if(a[i]&1)
cnt1++;
cnt2+=a[i]/2;
}
int ans=0;
if(cnt1)
ans=1+(cnt2/cnt1)*2;
else ans=2*cnt2;
printf("%d\n",ans);
}
}