给定大量手机用户通话记录,找出其中通话次数最多的聊天狂人。
输入格式:
输入首先给出正整数N(≤105),为通话记录条数。随后N行,每行给出一条通话记录。简单起见,这里只列出拨出方和接收方的11位数字构成的手机号码,其中以空格分隔。
输出格式:
在一行中给出聊天狂人的手机号码及其通话次数,其间以空格分隔。如果这样的人不唯一,则输出狂人中最小的号码及其通话次数,并且附加给出并列狂人的人数。
输入样例:
4
13005711862 13588625832
13505711862 13088625832
13588625832 18087925832
15005713862 13588625832
结尾无空行
输出样例:
13588625832 3
结尾无空行
分析:
散列表的设计:用号码的最后五位数作为关键字
使用分离链表存储并解决冲突问题
实现:(分离链接法实现散列表)
#include<iostream>
#include<vector>
#include<string>
#include<cmath>
using namespace std;
class node {
public:
string str;
int count;
node(string st) {
str = st, count =1;
}
};
int NextPrime(int x) {
int i, p = (x% 2) ? x + 2 :x + 1; /*从大于N的下一个奇数开始 */
while (1) {
for (i = (int)sqrt(p); i > 2; i--)
if (!(p % i)) break; /* p不是素数 */
if (i == 2) break; /* for正常结束,说明p是素数 */
else p += 2; /* 否则试探下一个奇数 */
}
return p;
}//找到大于x的最小素数作为散列表的大小
int HashFunc(int x,int size) {
return x % size;
}
int Trans(string str) {
string tem = str.substr(2, 5);
return atoi(tem.c_str());
}
int main() {
int N; cin >> N;
int n = N;
int size = NextPrime(2*N);
vector<vector<node>>Table(size, vector<node> {});
int max = 0; string record; int num = 1;
while (n--) {
string str1, str2;
cin >> str1 >> str2;
int map1 = HashFunc(Trans(str1),size);
bool flag = 0;
for (auto &content : Table[map1]) {
if (content.str == str1) {
content.count++; flag = 1;
if (content.count > max) {
max = content.count; record = str2;
num = 1;
}
else if (content.count == max)
record = record < str1 ? record : str1,num++;
break;
}
}
if (!flag)Table[map1].emplace_back(node(str1));
int map2 = HashFunc(Trans(str2), size);
flag = 0;
for (auto &content : Table[map2]) {
if (content.str == str2) {
content.count++; flag = 1;
if (content.count > max) {
max = content.count; record = str2; num = 1;
}
else if (content.count == max)
record = record < str2 ? record : str2, num++;
break;
}
}
if (!flag)Table[map2].emplace_back(node(str2));
}
cout << record << " " << max;
if (num != 1)cout<<" " << num;
}