题意:输入一些单词,找出所有满足如下条件的单词:单词不能通过排列得到输入中的另一个单词,在判读满足条件时不区分大小写,但输出时保留原串输出,按字典序输出(所有大写字母在小写字母前面)
本题是练习map用法的一道练习题
map容器是key-value对应的一种关联容器,即每个key对应一个value值
本题用到一些容器的基本操作,push_back(),insert()什么的,很方便,这就是STL的魅力
迭代器(用法类似指针)是个好东西,在STL中据说是三大支柱啊
如果难理解,不妨先回去复习以下指针的使用
以下是算法竞赛入门经典的刘汝佳老师的代码,我写了一点个人注释帮助大家理解
当然,要更好的了解map容器的用法还是要百度看其他博文,因为我也正在学(哈哈)
#include <iostream>
#include <map>
#include <string>
#include <cctype>
#include <vector>
#include <algorithm>
#include <cstdio>
using namespace std;
string s;
//建立map容器,特点是key-value对应关系,即一个string对应一个int值,例如dit[soon]=0;
map<string,int> dit;
//向量容器,类似于数组,操作也可以按数组方式操作,我这里尽量使用迭代器,多练练这个牛逼的东西总是好的呀
vector<string> tit;
vector<string> out;
//返回值是string类型
string vet(string s)
{
string ans=s;
//用迭代器遍历处理改变大写
for(string::iterator it=ans.begin();it!=ans.end();it++)
*it=tolower(*it);
//字典序排序
sort(ans.begin(),ans.end());
return ans;
}
int main()
{
freopen("in.txt","r",stdin);
while(cin >> s)
{
if(s[0]=='#')
break;
//把新读入的串存到向量容器里,方便之后遍历使用
tit.push_back(s);
//按题目要求处理新读入的串,即不能通过排列组合出现重复单词,把这个单词字典序排列就好了,还要改变大写
string r=vet(s);
//读入map容器,并获得其value值,即出现次数,0代表唯一
if(!dit.count(r))
dit[r]=0;
else
dit[r]=1;
}
//用迭代器进行遍历,单词唯一的就读入新的向量容器中
for(vector<string>::iterator it=tit.begin();it!=tit.end();it++)
if(dit[vet(*it)]==0)
out.push_back(*it);
//对向量容器进行字典序排序
sort(out.begin(),out.end());
//用迭代器遍历输出(用法类似指针,使用间接访问的形式)
for(vector<string>::iterator it=out.begin();it!=out.end();it++)
cout << *it << endl;
return 0;
}