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


易位构词 (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的字符串ans
		ans =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> 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值