HDU5744 Keep On Movin(贪心)
链接:http://acm.hdu.edu.cn/showproblem.php?pid=5744
题目
Time Limit:2000MS Memory Limit:65536KB
Description
Professor Zhang has kinds of characters and the quantity of the
i
-th character is
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
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个字符,然后给出你每个字符的数量,你来用他们组成若干字符串,保证每个字符串都是回文串。问你如何组字符串,可以使他们中最短的那串的长度最长。
分析
对于数量为1的字符,我们可以用2个相同字符来“嵌套”它。如{a,b和b}可以形成bab。故每2个相同字符可以形成一个“嵌套”。而大于1的奇数则可以转化为1个字符和若干对嵌套层。
故问题转化为计算嵌套层和单独字符数量的问题。见代码
源码
#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
#include<vector>
#include<algorithm>
#include<string>
#include<sstream>
#include<cmath>
#include<set>
#include<map>
#include<vector>
#include<stack>
#include<utility>
#include<sstream>
#define mem0(x) memset(x,0,sizeof x)
#define mem1(x) memset(x,-1,sizeof x)
#define dbug cout<<"here"<<endl;
//#define LOCAL
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int INF = 0x3f3f3f3f;
const int MAXN = 1e6+10;
const int MOD = 1000000007;
int main(){
#ifdef LOCAL
freopen("C:\\Users\\asus-z\\Desktop\\input.txt","r",stdin);
freopen("C:\\Users\\asus-z\\Desktop\\output.txt","w",stdout);
#endif
int t;
int n;
cin >> t;
while(t--){
cin >> n;
int tmp;
int cnt1 = 0;
int sumList = 0;
for(int i = 1; i <= n; ++i){
cin >> tmp;
if(tmp == 1)
cnt1++;
else if(!(tmp & 1))
sumList += tmp/2;
else{
sumList += tmp/2;
cnt1++;
}
}
if(cnt1 == 0)
cout << sumList*2 << endl;
else if(cnt1 > sumList)
cout << 1 << endl;
else
cout << 1+2*(sumList/cnt1) << endl;
}
return 0;
}