您的位置:首页 > 编程语言 > C语言/C++

Hlg 1618 词频统计.cpp【hash表 + 求字符串hash值】

2013-01-14 23:15 543 查看
[b]题意:[/b]

只有一组数据,数据量为20M

根据单词出现顺序输出出现次数..

[b]思路:[/b]

3种方法:① map ② BKDR求hash值<hash表的线性再散列方法或者是链表形式>

map的方法因为数据量很大..容易超时

[b]Tips:[/b]

※ BKDR求字符串hash值方法:

BKDR+线性再散列

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

const int maxn = 180000;

int BKDRHash(char *str)
{
int hash = 0;
while (*str)
{
hash = hash*31 + (*str++);
}
return (hash & 0x7FFFFFFF);
}

struct node
{
int count;
char *s;
}h[maxn];

int num[maxn]={0};
int tot = 0;
void hashinsert(char *str)
{
int val = BKDRHash(str)%maxn;
while (h[val].count != 0)
{
if (strcmp(h[val].s,str)==0)
{
h[val].count++;
break;
}
val = (val+1)%maxn;
}
if (h[val].count == 0)
{
int len = strlen(str);
h[val].s = (char*)malloc(sizeof(char)*(len+1));
strcpy(h[val].s,str);
h[val].count++;
num[++tot] = val;
}
}

char ss[3000000];

int main()
{
memset(h,0,sizeof(h));
while (scanf("%s",ss)!=EOF)
{
hashinsert(ss);
}
int i;
for (i=1; i<=tot; i++)
printf("%d\n",h[num[i]].count);
return 0;
}


[b]题目链接:[/b]

http://acm.hrbust.edu.cn/index.php?m=ProblemSet&a=showProblem&problem_id=1618
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: