USACO Section 1.2 Name That Number

/*
ID: lucien23
PROG: namenum
LANG: C++
*/

#include<iostream>
#include<fstream>
#include<set>
#include<string>
#include<map>
using namespace std;

int main()
{
	ifstream infile("namenum.in");
	ifstream inDict("dict.txt");
	ofstream outfile("namenum.out");
	if(!infile || !outfile || !inDict)
	{
		cout<<"file operation failure!"<<endl;
		return -1;
	}
	//记录数字和字母的匹配关系
	map<char,string> digit2chars;
	digit2chars['2']="ABC";
	digit2chars['3']="DEF";
	digit2chars['4']="GHI";
	digit2chars['5']="JKL";
	digit2chars['6']="MNO";
	digit2chars['7']="PRS";
	digit2chars['8']="TUV";
	digit2chars['9']="WXY";

	set<string> names;
	map<string,string> name2num;
	string strTemp;
	while(!inDict.eof())
	{
		//将字典中的名字转换成对应的数字串
		inDict>>strTemp;
		int len=strTemp.length();
		string destNum="";
		for (int i=0;i<len;i++)
		{
			for (int j=2;j<=9;j++)
			{
				string str=digit2chars[j+'0'];
				if(str.find(strTemp[i])!=-1)
				{
					destNum+=j+'0';
					break;
				}
			}
		}
		name2num[strTemp]=destNum;
	}

	string strNum;
	infile>>strNum;
	//比较查找对应的名称
	for (map<string,string>::iterator it=name2num.begin();it!=name2num.end();it++)
	{
		if(strNum==it->second)
			names.insert(it->first);
	}

	if(names.size()==0)
	{
		outfile<<"NONE"<<endl;
	}
	else
	{
		for (set<string>::iterator it=names.begin(); it!=names.end(); it++)
		{
			outfile<<*it<<endl;
		}
	}

	return 0;
}

你可能感兴趣的:(Algorithm,C++,USACO)