C. Make Palindrome
Time Limit: 20 Sec
Memory Limit: 256 MB
题目连接
http://codeforces.com/contest/600/problem/C
Description
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.
You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes.
You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
Input
The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.
Output
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
Sample Input
aabc
Sample Output
abba
HINT
题意
给你一个字符串,让你重新排列,并且你也可以修改一些字符
问你在保证修改最少的情况下,字典序最小的回文串是什么样子的?
题解:
串长为偶数则所有字母出现次数均为偶数,把所有出现次数为奇数的都换一个变成a即可,
串长为奇数,那么至多有一种字母出现次数为奇数,选取字典序最小的那种,其余出现次数为奇数的都换一个变成a即可
代码:
#include<iostream> #include<stdio.h> #include<algorithm> using namespace std; string s; int p[100]; int dp[1000100]; int main() { cin>>s; for(int i=0;i<s.size();i++) p[s[i]-'a']++; int d = s.size()-1; int flag = -1; for(int i=0;i<26;i++) { while(p[i]>=2) { flag++; dp[flag]=i; p[i]-=2; } } /* for(int i = odd.size() / 2 ; i < odd.size() ; ++ i ){ char r = odd[i].first; char l = odd[i-odd.size()/2].first; cnt[r]--; cnt[l]++; } */ for(int i=0;i<26;i++) { if(p[i]) { flag++; if(2*flag==d) { dp[flag]=i; break; } if(2*flag>d)break; dp[flag]=i; } } while(2*flag<d)flag=(d+1)/2; sort(dp,dp+flag); for(int i=0;i<flag;i++) dp[s.size()-i-1]=dp[i]; for(int i=0;i<s.size();i++) printf("%c",dp[i]+'a'); }