EOJ Monthly 2017.12 易位构词(贪心+STL特性容器 +头文件<bits/stdc++.h> )

来源:互联网 发布:js字符串叠加 编辑:程序博客网 时间:2024/06/06 06:44

易位构词 (anagram),指将一个单词中的字母重新排列,原单词中的每个字母都出现有且仅有一次。例如 "unce" 可以被易位构词成 "ecnu"。在某些情况下,要求重排而成的依然是一个单词,但本题没有这种要求,因为我们根本没有词典。我们所感兴趣的是,有些单词中的字母进行适当的重排后,可以使得构成的单词每个对应的位置上字母都不一样。例如 "unce" 和 "ecnu",就有 "u" ≠ "e", "n" ≠ "c", "c" ≠ "n", "e" ≠ "u"。现在给出一个单词,问是否存在这样一个重排。
Input
一行一个单词 s (1≤|s|≤105)。单词完全由 26 个小写英文字母构成。
Output
输出一个单词。如果有多解,输出任意解。如果不存在,输出 impossible。
Examples
input
unce
output
ecnu
input
aaaaaa
output
impossible 
思路:贪心,出现次数最多的字符串是最难处理的,在比赛中就因为这个处理不当,看了别人的博客之后,将出现次数最多的字母放在出现次数最少的字母那里,让次多的和次次多的填写到最多的位置(大意)。 
例:
5 4 3 2 1
4 3 2 1 5   (数字是代表字母本身而不是次数)
#include <bits/stdc++.h>  //using namespace std;string s;int main(){while(cin >> s){int cnt[26],flag=0;memset(cnt, 0, sizeof(cnt));for(int i = 0; i < s.size(); ++i){ //记录下各个字母出现的次数cnt[s[i] - 'a']++;}vector<pair<int,int> > g;   //定义了一个pair的二元组for(int i = 0; i < 26; ++i){if(cnt[i] > 0){g.push_back(make_pair(cnt[i], i));  //压入每个英文字母出现的次数 字母}}sort(g.begin(), g.end());    //按次数排序 利用了二元组sort的性质reverse(g.begin(), g.end());   //反转,排列变成从大到小string cur = "";               //定义一个空的字符串for(int i = 0; i < g.size(); ++i){for(int j = 1; j <= g[i].first; ++j){cur += 'a' + g[i].second;      //按英文字母出现次数从大到小的顺序构成字符串}}string ans = "";    //定义一个空的字符串int pos = g[0].first;int i = pos;          //一个字母出现最多的次数while(i < cur.size()){   //构造省略了出现次数最多字母的字符串cur的字符串ansans =ans+ cur[i++];}i = 0;while(i < pos){ans += cur[i++];   //将出现次数最多的字母加到字符串ans结尾}vector<int>x[26];      //定义一个x[26][]的数组for(int i = 0; i < ans.size(); ++i){x[cur[i] - 'a'].push_back(ans[i] - 'a');//x[cur字母][]=ans cur用ans代替}int poss[26];memset(poss, 0, sizeof(poss));string res = "";   //定义一个空的字符串for(int i = 0; i < s.size(); ++i){res+='a' + x[s[i] - 'a'][poss[s[i] - 'a']++];//poss从0开始计算}  // res+=后面的内容没有错误   res=res+后面的内容报错for(int i = 0; i < s.size(); ++i){if(s[i] == res[i]){cout<<"impossible"<<endl;flag=1;break;}}if(!flag)cout<<res<<endl;   }}
#include<bits/stdc++.h>这个头文件包含以下等等C++中包含的所有头文件: 
#include <iostream> 
#include <cstdio> 
#include <fstream> 
#include <algorithm> 
#include <cmath> 
#include <deque> 
#include <vector> 
#include <queue> 
#include <string> 
#include <cstring> 
#include <map> 
#include <stack> 
#include <set> 



原创粉丝点击