题意
Professor Zhang has kinds of characters and the quantity of the ii-th character is aiai. 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.
想法
先考虑构成回文串的规律:
- 偶数个相同字母能够成回文串
- 多个不同偶数回文串可以组合成新的偶数回文串
- 奇数个相同字母能够构成回文串
- 如果统计一个奇数回文串中不同字母出现次数的话,只能有一个字母出现次数为奇数(可以不严谨反证)
- 可以不断的在奇数串上添加偶数串,增加长度。反之,也可以从奇数串上剥离偶数回文串。
基于以上规律,可以发现,偶数回文串用起来更方便,条件不那么苛刻。这时我们就不用考虑字母之间的差异了,既然不同的偶数数量字母可以相互组合成回文串,那就把他们当成一个字母好了。
比如,假如给的字母都是偶数个的话,可以把所有字母一起组合成一个长的偶数回文串,就是答案。
假如只有一个字母给了奇数个,那么也可以把剩下的所有偶数个字母添加上去,形成一个回文串,也是答案。
如果存在多个字母为奇数个呢?
根据规律4,此时已经无法合成一个整体回文串了,必须要拆分成多个回文串。
为了使最短串最长,拆分的组数自然越少越好。所以,奇数数量的字母有多少个,就拆多少组。
为了计算方便,从奇数个字母的数量剥离直至该字母数量只剩下一个,剩下的扔进偶数字母的数量中。然后将偶数字母平均分配到每个组即可。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long int ll;
const int MAXN=100000+5;
ll es,on;
int n;
int cases;
int main(){
cin>>cases;
while(cases--){
es=on=0;
scanf("%d",&n);
for(int i=1;i<=n;i++){
ll tt;
scanf("%I64d",&tt);
if(!(tt%2))
es+=tt;
else{
on++;
es+=tt-1;
}
}
es/=2;
if(on)
printf("%I64d\n",(es/on)*2+1);
else
printf("%I64d\n",es*2);
}
return 0;
}
posted on
浙公网安备 33010602011771号