题目链接
关键点:
1、直接利用hash表的查找,插入等功能
2、如何输出答案:在扫描hash表时,遇到聊天数大的就记下号码和更新最大值,如果遇到聊天数相同的,就将个数加上1,并且更新最小的字符串
完整代码:
# include <stdio.h>
# include <math.h>
# include <stdlib.h>
# include <string.h>
# define KeyLength 11
# define MaxSize 300000
# define MAXD 5
typedef char ElementType [KeyLength+1];
typedef int Index;
typedef struct Node *PtrToNode;
struct Node{
ElementType Data;
PtrToNode Next;
int count;
};
typedef PtrToNode Position;
typedef PtrToNode List;
typedef struct HashNode *HashTable;
struct HashNode{
int TableSize;
List Heads;
};
int nextprime(int n)
{
int i;
int p = (n%2)? n+2: n+1;
while (p<=MaxSize)
{
for (i=sqrt(p); i>2; i--)
{
if (p%i==0) break;
}
if (i==2)
break;
p+=2;
}
return p;
}
HashTable CreateTable(int size)
{
HashTable H;
int i;
H = (HashTable)malloc(sizeof(struct HashNode));
H->TableSize = nextprime(size);
H->Heads = (List)malloc(sizeof(struct Node)*H->TableSize);
for (i=0; i<H->TableSize; i++)
{
H->Heads[i].Data[0] = '\0';
H->Heads[i].count = 0;
H->Heads[i].Next = NULL;
}
return H;
}
int Hash(int key, int p)
{
return key%p;
}
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;
}
void InsertHash(HashTable H, ElementType Key)
{
Position Pos, newnode;
Index p;
Pos = find(H, Key);
if (!Pos)
{
newnode = (Position)malloc(sizeof(struct Node));
strcpy(newnode->Data, Key);
newnode->count = 1;
p = Hash(atoi(Key+KeyLength-MAXD), H->TableSize);
newnode->Next = H->Heads[p].Next;
H->Heads[p].Next = newnode;
return ;
}
else
{
Pos->count++;
return ;
}
}
void ScanAndOutput(HashTable H)
{
int i, Maxcnt=0, Pcnt=0;
List ptr;
ElementType minphone;
minphone[0] = '\0';
for (i=0; i<H->TableSize; i++)
{
ptr = H->Heads[i].Next;
while (ptr)
{
if (Maxcnt<ptr->count)
{
Maxcnt = ptr->count;
Pcnt = 1;
strcpy(minphone, ptr->Data);
}
else if (Maxcnt == ptr->count)
{
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");
}
void DestoryHash(HashTable H)
{
List ptr, tmp;
for (int i=0; i<H->TableSize; i++)
{
ptr = H->Heads[i].Next;
while (ptr)
{
tmp = ptr->Next;
free(ptr);
ptr = tmp;
}
}
free(H->Heads);
free(H);
}
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);
InsertHash(H, key);
scanf("%s", key);
InsertHash(H, key);
}
ScanAndOutput(H);
DestoryHash(H);
return 0;
}