POJ解题报告——1002 487-3279
问题描述
输入一组电话(为了方便记忆存在带有大写字母的电话号),统计重复出现的电话号,标准化后按字典序输出
电话号码的可能格式如下
888-GLOP
TUT-GLOP
967-11-11
标准电话号码实例
888-4567 (3位+‘-’+4位)
字母和数字的映射关系如下
A, B, 和C 映射到 2
D, E, 和F 映射到 3
G, H, 和I 映射到 4
J, K, 和L 映射到 5
M, N, 和O 映射到 6
P, R, 和S 映射到 7
T, U, 和V 映射到 8
W, X, 和Y 映射到 9
没有Q和Z
详见 http://poj.org/problem?id=1002
解题思路
这题算比较简单的,但听说数据量比较大,算法不能太慢。这个算法跑了一秒左右,如果用字符存储电话,估计就GG了。
这里先将电话号码转换成int型,并采用map存储。
之后直接输出即可。
关于电话号码的转换,采用手工存了个字符表进去,可以不用多个if或者switch,兴许可以快一点。
代码如下
由于POJ莫名不能编译我的map.insert(),改用tel_table[tel]++;的形式插入新的电话。
cout的格式化输出也比较有趣,经常会忘记,需要#include 。
#include <iostream>
#include <string>
#include <map>
#include <iomanip>
using namespace std;
int main()
{
//预先输入字母映射表
int tonum[128] = { 0 };
for (int i = 0; i < 10; ++i)
tonum[48 + i] = i;
tonum['A'] = tonum['B'] = tonum['C'] = 2;
tonum['D'] = tonum['E'] = tonum['F'] = 3;
tonum['G'] = tonum['H'] = tonum['I'] = 4;
tonum['J'] = tonum['K'] = tonum['L'] = 5;
tonum['M'] = tonum['N'] = tonum['O'] = 6;
tonum['P'] = tonum['R'] = tonum['S'] = 7;
tonum['T'] = tonum['U'] = tonum['V'] = 8;
tonum['W'] = tonum['X'] = tonum['Y'] = 9;
map<int, int> tel_table;
int n, tel;
string str;
cin >> n;
while (n--)
{
//处理输入电话str,并转换成int型的tel
cin >> str;
tel = 0;
for (int i = 0; i < str.length(); ++i) {
if (str[i] == '-')
continue;
tel = tel * 10 + tonum[str[i]];
}
//将tel插入umap中
//pair<map<int, int>::iterator, bool> ret = tel_table.insert({ tel,1 });
//if (!ret.second)
// ++ret.first->second;
tel_table[tel]++;
}
//输出重复出现的电话
bool hasAns = false;
map<int, int>::iterator tel_it = tel_table.begin();
while (tel_it != tel_table.end()) {
if (tel_it->second <= 1) {
++tel_it;
continue;
}
hasAns = true;
cout << setfill('0') << setw(3) << tel_it->first / 10000 << "-";
cout << setfill('0') << setw(4) << tel_it->first % 10000 << " ";
cout << tel_it->second << endl;
++tel_it;
}
if (!hasAns)
cout << "No duplicates." << endl;
return 0;
}
测试数据
为了方便只看到这篇文章的人测试。这里给出POJ的测试数据
Sample Input
12
4873279
ITS-EASY
888-4567
3-10-10-10
888-GLOP
TUT-GLOP
967-11-11
310-GINO
F101010
888-1200
-4-8-7-3-2-7-9-
487-3279
Sample Output
310-1010 2
487-3279 4
888-4567 3