原题链接:
https://pintia.cn/problem-sets/15/problems/722
思路:用map(map<string,int>)解题,使用map的查找函数进行判断是否已经存在该号码,存在加上一次,不存在加上该元素,并且赋值为1,最后再遍历两遍map,第一遍找出最大次数的号码,第二遍找出相同次数的号码个数,并且修改我们的号码(号码最小的并且是次数最多的)。
易错点:不能在最后只遍历一遍map,同时修改“最大”次数和号码,因为在过程当中的次数并不是真正的最大次数,也不能修改号码,因为可能存在我次数少但是我号码小的情况,此时我们就不能得到最大次数时候的最小号码。
原题AC代码:
#include<iostream>
#include<map>
#include<cmath>
using namespace std;
int main() {
int n;
string s1, s2;
cin >> n;
map<string, int>p;
for (int i = 0; i < n; i++) {
cin >> s1 >> s2;
map<string, int>::iterator f1 = p.find(s1);
map<string, int>::iterator f2 = p.find(s2);
if (f1 != p.end()) {
p[s1]++;
}
else {
p[s1] = 1;
}
if (f2 != p.end()) {
p[s2]++;
}
else {
p[s2] = 1;
}
}
map<string, int>::iterator pos;
int mmax = -1, cs = 1;
string hm = "99999999999";
for (pos = p.begin(); pos != p.end(); pos++) {
//mmax = max(mmax, pos->second);
if (mmax < pos->second) {
mmax = pos->second;
hm = pos->first;
}
}
for (pos = p.begin(); pos != p.end(); pos++) {
if (pos->first == hm) {
continue;
}
if (pos->second == mmax) {
cs++;
if (hm > pos->first) {
hm = pos->first;
}
}
}
cout << hm << " " << mmax;
if (cs != 1) {
cout << " " << cs;
}
return 0;
}