11-散列1 电话聊天狂人 (25分)
给定大量手机用户通话记录,找出其中通话次数最多的聊天狂人。
输入格式:
输入首先给出正整数NNN(≤105\le 10^5≤105),为通话记录条数。随后NNN行,每行给出一条通话记录。简单起见,这里只列出拨出方和接收方的11位数字构成的手机号码,其中以空格分隔。
输出格式:
在一行中给出聊天狂人的手机号码及其通话次数,其间以空格分隔。如果这样的人不唯一,则输出狂人中最小的号码及其通话次数,并且附加给出并列狂人的人数。
输入样例:
4
13005711862 13588625832
13505711862 13088625832
13588625832 18087925832
15005713862 13588625832
输出样例:
13588625832 3
#include "stdio.h"
#include "stdlib.h"
#include "math.h"
#include "string.h"
#define KEYLENGTH 11
#define MAXD 5
typedef char ElementType[KEYLENGTH+1];
typedef unsigned 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 head;
};
int NextPrime(int N) //散列表的长度一般是比预计个数大的最小素质,这里就是求最小素数
{
int i;
if(N%2==0)
N++;
for(;;N+=2)
{
for(i=3;i*i<=N;i+=2)
if(N%i==0)
break;
if(i*i>N)
return N;
}
}
HashTable CreateTable(int HashSize)
{
HashTable H;
int i;
HashSize=NextPrime(HashSize);
H=(HashTable)malloc(sizeof(struct TblNode));
H->TableSize=HashSize;
H->head=(List)malloc(HashSize*sizeof(struct LNode));
for(i=0;i<HashSize;i++)
{
H->head[i].Data[0]='\0';
H->head[i].Next=NULL;
}
return H;
}
int Hash(int key,int p)
{
return key%p;
}
Position Find(HashTable H,ElementType KEY)
{
Index pos;
Position p;
pos=Hash(atoi(KEY+KEYLENGTH-MAXD),H->TableSize);
p=H->head[pos].Next;
while(p&&strcmp(KEY,p->Data))
{
p=p->Next;
}
return p;
}
void Insert(HashTable H,ElementType Key)
{
Position P,NewNode;
Index pos;
P=Find(H,Key);
if(!P)
{
NewNode=(Position)malloc(sizeof(struct LNode));
strcpy(NewNode->Data,Key);
NewNode->Count=1;
pos=Hash(atoi(Key+KEYLENGTH-MAXD),H->TableSize);
NewNode->Next=H->head[pos].Next;
H->head[pos].Next=NewNode;
}
else
{
P->Count++;
}
}
void ScanAndOutput(HashTable H)
{
int i,Maxcnt=0,Pcnt=0;
ElementType Minphone;
Position p;
Minphone[0]='\0';
for(i=0;i<H->TableSize;i++)
{
p=H->head[i].Next;
while(p!=NULL)
{
if(p->Count>Maxcnt)
{
Maxcnt=p->Count;
strcpy(Minphone,p->Data);
Pcnt=1;
}
else if(p->Count==Maxcnt)
{
if(strcmp(Minphone,p->Data)>0)
strcpy(Minphone,p->Data);
Pcnt++;
}
p=p->Next;
}
}
printf("%s %d",Minphone,Maxcnt);
if(Pcnt>1)
printf(" %d",Pcnt);
printf("\n");
}
int main()
{
int i,N;
HashTable H;
ElementType KEY;
scanf("%d",&N);
H=CreateTable(N);
for(i=0;i<2*N;i++)
{
scanf("%s",&KEY);
Insert(H,KEY);
}
ScanAndOutput(H);
return 0;
}
pta试题训练
最新推荐文章于 2024-05-15 23:33:01 发布