5-14 电话聊天狂人 (25分)
感想:不会哈希表的可以通过做这道题入门哈希表
给定大量手机用户通话记录,找出其中通话次数最多的聊天狂人。
输入格式:
输入首先给出正整数N(≤105),为通话记录条数。随后N行,每行给出一条通话记录。简单起见,这里只列出拨出方和接收方的11位数字构成的手机号码,其中以空格分隔。
输出格式:
在一行中给出聊天狂人的手机号码及其通话次数,其间以空格分隔。如果这样的人不唯一,则输出狂人中最小的号码及其通话次数,并且附加给出并列狂人的人数。
输入样例:
4
13005711862 13588625832
13505711862 13088625832
13588625832 18087925832
15005713862 13588625832
输出样例:
13588625832 3
#include<iostream>
#include<algorithm>
#include<vector>
#include <cstdio>
using namespace std;
int count1=1;//全局变量
int max_time=0;
long min_number=999999999999;
struct tele_number{//使用链表创建哈希表
int count;
long tele;
tele_number* Next;
};
tele_number b[200000];//因为最大N是100000,故最多有200000组数据
tele_number* Find(long n){ // 找到哈希表中某元素对应的位置
int t=0;
long m=n;
tele_number* a;
if(n%10==1)//自定义的哈希函数
t+=100000;
n/=10;
n%=100000;
t+=n;
a=&b[t];
if(a->tele==-1){
a->tele=m;
return a;
}
while(a->tele!=m){
if(a->Next==NULL){
a->Next=(tele_number*)malloc(sizeof(tele_number));
a=a->Next;
a->tele=m;
a->count=0;
a->Next=NULL;
break;
}
else
a=a->Next;
}
return a;
}
void insert(long temp1){//插入哈希表的元素如已插入则计算重复次数
tele_number* s=Find(temp1);
s->count++;
if(s->count>max_time){
max_time++;
//cout<<s->tele<<"*:"<<s->count<<">"<<max_time;
min_number=temp1;
count1=1;
}
else if(s->count==max_time){
count1++;
if(temp1<min_number)
min_number=temp1;
}
}
int main(){
int N,i;
cin>>N;
long temp1,temp2;//电话序列
for(i=0;i<200000;i++){
b[i].count=0;
b[i].Next=NULL;
b[i].tele=-1;
}
for(i=0;i<N;i++){
scanf("%ld %ld",&temp1,&temp2);
insert(temp1);
insert(temp2);
}
printf("%ld %d",min_number,max_time);
if(count1>1)
printf(" %d",count1);
cout<<endl;
}
感想:不会哈希表的可以通过做这道题入门哈希表