11-散列1 电话聊天狂人 (25分)
看了姥姥的数据结构小白专场,把代码组合起来的,方便自己以后查看。原题链接
给定大量手机用户通话记录,找出其中通话次数最多的聊天狂人。
输入格式:
输入首先给出正整数N(≤105),为通话记录条数。随后N行,每行给出一条通话记录。简单起见,这里只列出拨出方和接收方的11位数字构成的手机号码,其中以空格分隔。
输出格式:
在一行中给出聊天狂人的手机号码及其通话次数,其间以空格分隔。如果这样的人不唯一,则输出狂人中最小的号码及其通话次数,并且附加给出并列狂人的人数。
输入样例:
4
13005711862 13588625832
13505711862 13088625832
13588625832 18087925832
15005713862 13588625832
输出样例:
13588625832 3
实现代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#define KEYLENGTH 11
#define MAXTABLESIZE 1000000
#define MAXD 5
typedef char ElementType[KEYLENGTH+1];
typedef int Index; //散列地址类型
typedef struct LNode *PtrToLNode;
struct LNode{
ElementType Data;
PtrToLNode Next;
int Count;
};
typedef PtrToLNode Position;
typedef PtrToLNode List;
typedef struct TblNode *HashTable;
struct TblNode{
int TableSize;
List Heads;
};
void ScanAndOutput( HashTable H )
{
int i, MaxCnt = 0;
int PCnt = 0;
ElementType MinPhone;
List Ptr;
MinPhone[0] = '\0';
for(i=0; i<H->TableSize; ++i)
{
Ptr = H->Heads[i].Next;
while (Ptr)
{
if(Ptr->Count > MaxCnt){
MaxCnt = Ptr->Count;
strcpy(MinPhone, Ptr->Data);
PCnt = 1;
}else if(Ptr->Count == MaxCnt){
PCnt ++;
if(strcmp(MinPhone, Ptr->Data)>0){
strcpy(MinPhone, Ptr->Data);
}
}
Ptr = Ptr->Next;
}
}
printf("%s %d", MinPhone, MaxCnt);
if(PCnt>1) printf(" %d", PCnt);
printf("\n");
}
int Hash (int Key, int P)
{
return Key%P;
}
int NextPrime(int N)
{
int i, p = (N%2)?N+2 : N+1;
while (p<=MAXTABLESIZE){
for(i=(int)sqrt(p); i>2; i--)
{
if(!(p%i)) break;
}
if(i==2) break;
else p += 2;
}
return p;
}
HashTable CreateTable( int TableSize )
{
HashTable H;
int i;
H = (HashTable)malloc(sizeof(struct TblNode));
H->TableSize = NextPrime(TableSize);
H->Heads = (List)malloc(H->TableSize*sizeof(struct LNode));
for(i=0; i<H->TableSize; i++){
H->Heads[i].Data[0] = '\0';
H->Heads[i].Next = NULL;
H->Heads[i].Count = 0;
}
return H;
}
Position Find(HashTable H, ElementType Key)
{
Position P;
Index Pos;
Pos = Hash(atoi(Key+KEYLENGTH-MAXD), H->TableSize);
P = H->Heads[Pos].Next;
while (P && strcmp(P->Data, Key))
P = P->Next;
return P;
}
bool Insert(HashTable H, ElementType Key)
{
Position P, NewCell;
Index Pos;
P = Find(H, Key);
if( !P ){
NewCell = (Position)malloc(sizeof(struct LNode));
strcpy(NewCell->Data, Key);
NewCell->Count = 1;
Pos = Hash(atoi(Key+KEYLENGTH-MAXD), H->TableSize);
NewCell->Next = H->Heads[Pos].Next;
H->Heads[Pos].Next = NewCell;
return true;
}else{
P->Count++;
return false;
}
}
void DestroyTable( HashTable H )
{
int i;
Position P, Tmp;
/* 释放每个链表的结点 */
for( i=0; i<H->TableSize; i++ ) {
P = H->Heads[i].Next;
while( P ) {
Tmp = P->Next;
free( P );
P = Tmp;
}
}
free( H->Heads ); /* 释放头结点数组 */
free( H ); /* 释放散列表结点 */
}
int main()
{
int i, N;
ElementType Key;
HashTable H;
scanf("%d", &N);
H = CreateTable(N*2);
for(i=0; i<N; ++i)
{
scanf("%s", Key); Insert( H, Key );
scanf("%s", Key); Insert( H, Key );
}
ScanAndOutput( H );
DestroyTable( H );
return 0;
}
运行结果: