uva156 Ananagrams (stl map的使用)

这个题目是刘汝佳的算法竞赛入门经典上的例题,为了加深印象来写题解了~

题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=19294

输入一些单词,找出所有满足如下条件的单词:该单词不能通过字母重排,得到输入文本中的另外一个单词。在判断是否满足条件时,字母不区分大小写,但在输出的时候保留输入时的大小写,按字典序进行排列。

样例输入:

ladder came tape soon leader acme RIDE lone Dreis peat
 ScAlE orb  eye  Rides dealer  NotE derail LaCeS  drIed
noel dire Disk mace Rob dries
#

样例输出:

Disk
NotE
derail
drIed
eye
ladder
soon


map,就是键(key)到值(value)的映射,因为重载了[]运算符,map 就像数组的高级版

例如这样定义 map<string,int> month_name来建立月份名字到月份编号的映射

像这样 month["JULY"]=7,month["SEPTEMBER"]=9,来赋值;

#include <vector>
#include <algorithm>
#include <map>
#include <cctype>
#include <iostream>
#include <string>
using namespace std;
string change(string s)//把字符串全部变成小写,并且排序,,这样所以的字符串都被“标准化”了,这样“可通过重排变成一样”的串就方便统计了。
{
	for(int i=0;i<s.length();i++)
	{
		s[i]=tolower(s[i]);
	}
	sort(s.begin(),s.end());
	return s;
}
int main()
{
	string s;
	map<string,int>mp;
	vector<string>words;
	while(cin>>s)
	{
		if(s[0]=='#')//输入终止标志
			break;
		string r=change(s);
		if(!mp.count(r))
			mp[r]=0;
		mp[r]++;//统计重复次数
		words.push_back(s);
	}
	vector <string>ans;
	for(int i=0;i<words.size();i++)
	{
		if(mp[change(words[i])]==1)//如果只出现一次,则满足题目要求
			ans.push_back(words[i]);
	}
	sort(ans.begin(),ans.end());
	for(int i=0;i<ans.size();i++)
		cout<<ans[i]<<endl;
}


posted @ 2015-05-05 22:14  编程菌  阅读(175)  评论(0编辑  收藏  举报