题目
给定大量手机用户通话记录,找出其中通话次数最多的聊天狂人。
输入格式:
输入首先给出正整数N(≤105),为通话记录条数。随后N行,每行给出一条通话记录。简单起见,这里只列出拨出方和接收方的11位数字构成的手机号码,其中以空格分隔。
输出格式:
在一行中给出聊天狂人的手机号码及其通话次数,其间以空格分隔。如果这样的人不唯一,则输出狂人中最小的号码及其通话次数,并且附加给出并列狂人的人数。
输入样例:
4
13005711862 13588625832
13505711862 13088625832
13588625832 18087925832
15005713862 13588625832
输出样例:
13588625832 3
解法
思路
- 散列表的长度可以设为3*N,采用线性探测的方式进行查找
- 哈希函数直接用除留求余法即可,用电话号码除以散列表长度,求余即可。
- 存储电话号码需要用long long int类型,相应的scanf("%lld", &key)
- 与常规哈希表的Cell类型不同,这里直接用InputTime代替Info来标记元素状态,InputTime=0,说明此位置为空,InputTime不为0,那就代表出现的次数,在最后输出的时候找到输出次数的最大值就好了。
- 需要两次遍历,第一次遍历,找InputTime的最大值,第二次遍历找InputTime的最大值对应的最小电话号码,最后按要求输出即可
实现
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define MAXNUMBER pow(10,12)
typedef long long int EleType;
typedef struct HashEntry Cell;
struct HashEntry
{
EleType Data;
int InputTime;
};
typedef struct TblNode *HashTable;
struct TblNode
{
int TableSize;
Cell *Cells;
};
HashTable CreateTable(int N)
{
HashTable H = (HashTable)malloc(sizeof(struct TblNode));
H->TableSize = 3*N;
H->Cells = (Cell*)malloc(H->TableSize*sizeof(struct HashEntry));
for(int i=0; i<H->TableSize; i++)
H->Cells[i].InputTime = 0;
return H;
}
int Hash(HashTable H, EleType key)
{
return key%H->TableSize;
}
int LinearFind(HashTable H, EleType key)
{
int CurPos, NewPos;
CurPos = NewPos = Hash(H, key);
int count = 0;
while(H->Cells[NewPos].InputTime != 0 && H->Cells[NewPos].Data != key)
{
count++;
NewPos = CurPos + count;
if(NewPos>=H->TableSize)
NewPos = NewPos%H->TableSize;
}
return NewPos;
}
void Insert(HashTable H, EleType key)
{
int Pos = LinearFind(H, key);
if(H->Cells[Pos].InputTime == 0)
{
H->Cells[Pos].Data = key;
H->Cells[Pos].InputTime = 1;
}
else
{
H->Cells[Pos].InputTime++;
}
}
int FindMaxInputTime(HashTable H)
{
int i,Max;
Max = 0;
for(i=0; i<H->TableSize; i++)
{
if(H->Cells[i].InputTime>Max)
Max = H->Cells[i].InputTime;
}
return Max;
}
void PrintResults(HashTable H)
{
int MaxTimes = FindMaxInputTime(H);
EleType MinNumber = MAXNUMBER;
int count = 0;
int i;
for(i=0; i<H->TableSize; i++)
{
if(H->Cells[i].InputTime == MaxTimes)
{
count++;
if(H->Cells[i].Data<MinNumber)
MinNumber = H->Cells[i].Data;
}
}
printf("%lld ", MinNumber);
printf("%d", MaxTimes);
if(count>1)
printf(" %d", count);
}
int main()
{
int N,i;
EleType key;
scanf("%d", &N);
HashTable H = CreateTable(N);
for(i=0; i<2*N; i++)
{
scanf("%lld", &key);
Insert(H, key);
}
PrintResults(H);
return 0;
}