#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct ListNode *Position;
typedef struct ListNode{
char PhoneNum[12];
int cnt;
Position Next;
} *List;
typedef struct HashTbl{
int TableSize;
List *TheLists;//建立一个ListNode的指针数组
} *HashTable;
int NextPrime(int x);
HashTable InitializeTable(int TableSize);
void DestroyTable(HashTable H);
Position Find(char Key[], HashTable H);
void Insert(char Key[], HashTable H);
int Hash(int Key, int TableSize);
void FindMax(HashTable H);
int main(int argc, char const *argv[])
{
// freopen("test.txt", "r", stdin);
int N;
scanf("%d", &N);
HashTable H = InitializeTable(2 * N);
char send[12], rec[12];
for (int i = 0; i < N; i++){
scanf("%s %s\n", send, rec);
Insert(send, H), Insert(rec, H);
}
FindMax(H);
DestroyTable(H);
return 0;
}
int NextPrime(int x)
{
int i;
for (int Next = x; ; Next++){
for (i = 2; i * i <= Next; i++)
if (Next % i == 0)
break;
if (i * i > Next)
return Next;
}
}
HashTable InitializeTable(int TableSize)
{
HashTable H;
H = (HashTable)malloc(sizeof(struct HashTbl));
H->TableSize = NextPrime(TableSize);
H->TheLists = (List*)malloc(sizeof(List)*H->TableSize);
for (int i = 0; i != H->TableSize; i++){
H->TheLists[i] = (List)malloc(sizeof(struct ListNode));
H->TheLists[i]->Next = NULL;
}
return H;
}
void DestroyTable(HashTable H)
{
for (int i = 0; i < H->TableSize; i++)
free(H->TheLists[i]);
free(H->TheLists);
free(H);
}
Position Find(char Key[], HashTable H)
{
Position P;
List L;
L = H->TheLists[Hash(atoi(Key + 6), H->TableSize)];
P = L->Next;
while (P != NULL && strcmp(P->PhoneNum, Key))
P = P->Next;
return P;
}
void Insert(char Key[], HashTable H)
{
Position Pos, Tmp;
List L = H->TheLists[Hash(atoi(Key + 6), H->TableSize)];
Pos = Find(Key, H);
if (Pos == NULL){
Tmp = (List)malloc(sizeof(struct ListNode));
strcpy(Tmp->PhoneNum, Key);
Tmp->cnt = 1;
Tmp->Next = L->Next;
L->Next = Tmp;
} else {
(Pos->cnt)++;
}
}
int Hash(int Key, int TableSize)
{
return (Key % TableSize);
}
void FindMax(HashTable H)
{
Position P;
int maxcnt = 0, maxSame = 1;
char MinPhone[12];
for (int i = 0; i < H->TableSize; i++){
P = H->TheLists[i]->Next;
while (P != NULL){
if (P->cnt > maxcnt){
strcpy(MinPhone, P->PhoneNum);
maxcnt = P->cnt;
maxSame = 1;
} else if (P->cnt == maxcnt){
if (strcmp(MinPhone, P->PhoneNum) > 0)
strcpy(MinPhone, P->PhoneNum);
maxSame++;
}
P = P->Next;
}
}
printf("%s %d", MinPhone, maxcnt);
if (maxSame > 1)
printf(" %d", maxSame);
}
11-散列1 电话聊天狂人
最新推荐文章于 2024-03-24 19:00:00 发布