您的位置:首页 > 其它

11-散列1 电话聊天狂人(25 分)

2017-11-18 14:50 731 查看


11-散列1 电话聊天狂人(25 分)

给定大量手机用户通话记录,找出其中通话次数最多的聊天狂人。


输入格式:

输入首先给出正整数N(≤10​5​​),为通话记录条数。随后N行,每行给出一条通话记录。简单起见,这里只列出拨出方和接收方的11位数字构成的手机号码,其中以空格分隔。


输出格式:

在一行中给出聊天狂人的手机号码及其通话次数,其间以空格分隔。如果这样的人不唯一,则输出狂人中最小的号码及其通话次数,并且附加给出并列狂人的人数。


输入样例:

4
13005711862 13588625832
13505711862 13088625832
13588625832 18087925832
15005713862 13588625832


输出样例:

13588625832 3


作者: DS课程组
单位: 浙江大学
时间限制: 400ms
内存限制: 64MB
代码长度限制: 16KB

思路:一道简单的散列表。取最后5位作为key,冲突时链表插入,相等时计数器加1。

代码:

#include<stdio.h>
#include<string>
long long max = 0, people = 0, id = -1;
struct node {
long long date;
long long count;
struct node *next;
};
typedef struct node * List;
struct hashtable {
long long table;
List * list;
};
typedef struct hashtable * hash;
typedef struct node * position;
long long nextprime(long long n)
{
long long i, j;
for (i = n + 1;; i++)
{
for (j = 2; j < i / 2; j++)
if (!(i%j)) break;
if (j == i / 2) return i;
}
}
hash create(long long n)
{
hash h = (hash)malloc(sizeof(hashtable));
h->table = nextprime(n);
h->list = (List *)malloc(sizeof(node)*(int)h->table);
for (long long i = 0; i < h->table; i++)
{
h->list[i] = (List)malloc(sizeof(node));
h->list[i]->count = 0;
h->list[i]->date = 0;
h->list[i]->next = NULL;
}
return h;
}
void insert(hash h, long long key)
{
long long k = key % h->table;
position p = h->list[k]->next;
while (p)
{
if (p
4000
->date == key) break;
p = p->next;
}
if (!p)
{
p = (position)malloc(sizeof(node));
p->date = key;
p->count = 1;
p->next = h->list[k]->next;
h->list[k]->next = p;
}
else p->count++;

if (p->count > max) {
max = p->count;
people = 1;
id = p->date;
}
else if (p->count == max) {
if (id == -1) id = key;
else if (id > key) id = key;
people++;
}
}
void searchAndOut(hash h)
{
if (people == 1) printf("%lld %lld\n", id, max);
else printf("%lld %lld %lld\n", id, max, people);
}
int main()
{
long long n, a, b;
scanf("%lld", &n);
hash h = create(2 * n);
for (long long i = 0; i < n; i++)
{
scanf("%lld %lld", &a, &b);
insert(h, a);
insert(h, b);
}
searchAndOut(h);
}


结尾:本来直接想把散列表定义拷上去的,但是学校网站进不去了。于是准备手撸一个,结果一路顺畅 (*^▽^*)

           交上去以后最后一个测试点过不去,很郁闷,查了半个多小时才发现 把'>' 写成 ‘<’     (╯‵□′)╯︵┻━┻

           现在想想完全可以定义一个struct node,然后用vector实现……下次有空试试
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  PTA 散列表