題目描述:
給定大量手機用戶通話記錄,找出其中通話次數最多的聊天狂人。
輸入格式:
輸入首先給出正整數N(≤105),爲通話記錄條數。隨後N行,每行給出一條通話記錄。簡單起見,這裏只列出撥出方和接收方的11位數字構成的手機號碼,其中以空格分隔。
輸出格式:
在一行中給出聊天狂人的手機號碼及其通話次數,其間以空格分隔。如果這樣的人不唯一,則輸出狂人中最小的號碼及其通話次數,並且附加給出並列狂人的人數。
輸入樣例:
4
13005711862 13588625832
13505711862 13088625832
13588625832 18087925832
15005713862 13588625832
輸出樣例:
13588625832 3
根據慕課上老師講的代碼打的
代碼如下:
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
#define KEYLENGTH 11 // 關鍵字符串的最大長度
#define MAXTABLESIZE 1000000
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; // 指向鏈表頭結點的數組
};
int Hash(int Key, int P)
{
return Key % P;
}
// 返回大於N不超過MAXTABLESIZE的最小素數
int NextPrime(int N)
{
int i, p = (N % 2) ? N+2 : N+1; // 從大於N的下一個奇數開始
while(p <= MAXTABLESIZE)
{
for(i = (int)sqrt(p); i > 2; i--)
if (!p % i) // p不是素數
break;
if (i == 2) // for循環正常結束,說明p是素數
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-5), H->TableSize);
P = H->Heads[Pos].Next; // 從鏈表的第一個節點開始
// 當未到表尾且Key未找到
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 - 5), H->TableSize);
NewCell->Next = H->Heads[Pos].Next;
H->Heads[Pos].Next = NewCell;
return true;
}
// 關鍵詞已存在
else
{
P->Count++;
return false;
}
}
void ScanAndOutput(HashTable H)
{
int i, MaxCnt, PCnt;
MaxCnt = 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 main()
{
int N, i;
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);
return 0;
}