Educational Codeforces Round 2 C. Make Palindrome 贪心
2015-11-29 20:45
423 查看
C. Make Palindrome
Time Limit: 20 SecMemory Limit: 256 MB
题目连接
http://codeforces.com/contest/600/problem/CDescription
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'); }
相关文章推荐
- HDU 5351 MZL's Border (多校联合第5场1009)
- 我用u盘安装centos操作系统时遇到的问题
- 【Eclipse for IAR】使用 Eclipse 编写 IAR 程序
- python操作mongodb数据库
- 【LabVIEW花样翻新】使用子面板技术进行动态的界面加载
- hpu--1717
- 杂项(1)
- DIV+JS对话框
- CK-player调用
- Toolbar的简单介绍和如何简单自定义toolbar
- 操作系统概念 管程Java代码实现
- 击溃360手机卫士的三大防护
- 一位90后女生的IT之旅
- C#拆箱与装箱
- ACM组队安排 (DFS+计数原理)
- 模块、过程和变量
- java+struts+spring验证用户名是否存在
- 一个简单的表单验证JS
- leetcode 81:Search in Rotated Sorted Array II
- 《代码整洁之道》-- 写代码时需要注意的命名技巧