给定大量手机用户通话记录,找出其中通话次数最多的聊天狂人。
输入格式:
输入首先给出正整数N(≤105),为通话记录条数。随后N行,每行给出一条通话记录。简单起见,这里只列出拨出方和接收方的11位数字构成的手机号码,其中以空格分隔。
输出格式:
在一行中给出聊天狂人的手机号码及其通话次数,其间以空格分隔。如果这样的人不唯一,则输出狂人中最小的号码及其通话次数,并且附加给出并列狂人的人数。
输入样例:
4
13005711862 13588625832
13505711862 13088625832
13588625832 18087925832
15005713862 13588625832
结尾无空行
输出样例:
13588625832 3
这题在mooc陈越老师那儿已经说过思路了,将每个函数模块写出来就行了
//11-散列1 电话聊天狂人 (25 分)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
typedef struct LNode* PtrToNode;
struct LNode{
char Data[12];
int count;
PtrToNode Next;
};
typedef PtrToNode List;typedef struct TblNode* HashTable;
struct TblNode{
int TableSize;
List Heads;
};
int NextPrime(int x);
HashTable CreatTable(int N);
bool Insert(HashTable H, char Key[]);
PtrToNode Find(HashTable H, char Key[]);
int Hash(int Key, int P);
void ScanMax(HashTable H);
void Destory(HashTable H);int main()
{
int N, i;
char Key[12];
scanf("%d", &N);
HashTable H = CreatTable(N);
for(i=0;i<N;i++){
scanf("%s", Key);
Insert(H, Key);
scanf("%s", Key);
Insert(H, Key);
}
ScanMax(H);
Destory(H);
}int NextPrime(int x)
{
x++;
while(1)
{
int flag = 1;
for(int i=2;i<=sqrt(x);i++){
if(x%i==0){
flag = 0;
break;
}
}
if(flag) return x;
x+=2;
}
}HashTable CreatTable(int N)
{
HashTable H;
int i;
H = (HashTable) malloc (sizeof(struct TblNode));
H->TableSize = NextPrime(N*2);
H->Heads = (List) malloc (H->TableSize*sizeof(struct LNode));
for(i=0;i<H->TableSize;i++){ //初始化
H->Heads[i].count = 0;
H->Heads[i].Data[0] = '\0';
H->Heads[i].Next = NULL;
}
return H;
}bool Insert(HashTable H, char Key[])
{
PtrToNode P = Find(H, Key);
if(!P){
PtrToNode NewNode = (PtrToNode) malloc (sizeof(struct LNode));
int position = Hash(atoi(Key+6), H->TableSize);
strcpy(NewNode->Data, Key);
NewNode->count = 1;
NewNode->Next = H->Heads[position].Next;
H->Heads[position].Next = NewNode;
return true;
}
else{
P->count++;
return false;
}
}PtrToNode Find(HashTable H, char Key[])
{
PtrToNode P;
int position;
position = Hash(atoi(Key+6), H->TableSize);
P = H->Heads[position].Next;
while(P&&strcmp(P->Data, Key)){
P = P->Next;
}
return P;
}int Hash(int Key, int P)
{
return Key%P;
}void ScanMax(HashTable H)
{
int i, MaxCount=0, equal=0;
char MinPhone[12];
MinPhone[0] = '\0';
List Ptr;
for(i=0;i<H->TableSize;i++){
Ptr = H->Heads[i].Next;
while(Ptr){
if(Ptr->count > MaxCount){
MaxCount = Ptr->count;
strcpy(MinPhone, Ptr->Data);
equal = 1;
}
else if(Ptr->count == MaxCount){
equal++;
if(strcmp(MinPhone, Ptr->Data) > 0) strcpy(MinPhone, Ptr->Data);
}
Ptr = Ptr->Next;
}
}
printf("%s %d", MinPhone, MaxCount);
if(equal>1) printf(" %d", equal);
}void Destory(HashTable H)
{
List Ptr;
for(int i=0;i<H->TableSize;i++){
Ptr = H->Heads[i].Next;
while(Ptr){
H->Heads[i].Next = Ptr->Next;
free(Ptr);
Ptr = H->Heads[i].Next;
}
}
free(H->Heads);
free(H);
}