pku 2418 Hardwood Species 字典树

http://poj.org/problem?id=2418

字典数编号,统计每个单词出现的次数,然后计算频率:

View Code
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#define maxn 10007
using namespace std;


struct node
{
int flag;
node *next[100];
}*head,H[999999];
int pos;
int L;
struct mm
{
char s[33];
}pp[maxn];
int cmp(mm a,mm b)
{
return strcmp(a.s,b.s) < 0;
}
node* newnode()
{
node *q = &H[pos++];
for (int i = 0; i< 100; ++i)
q->next[i] = NULL;
q->flag = 0;
return q;
}
void insert(char *s)
{
int i,k;
//printf(">>%s\n",s);
int len = strlen(s);
node *p = head;
for (i = 0; i < len; ++i)
{
k = s[i] - 32;
if (p->next[k] == NULL)
p->next[k] = newnode();
p = p->next[k];
}
if (p->flag == 0)
{
strcpy(pp[L++].s,s);
p->flag++;
}
else
p->flag++;

}
int find(char *s)
{
int i,k;
int len = strlen(s);
node *p = head;
for (i = 0; i < len; ++i)
{
k = s[i] - 32;
if (p->next[k] == NULL)
{
return 0;
}
p = p->next[k];
}
return p->flag;
}

int main()
{
//freopen("in.txt","r",stdin);
char ch[33];
L = pos = 0;
head = &H[pos++];
int sum = 0;
while (gets(ch) != NULL)
{
sum++;
insert(ch);
}
sort(pp,pp + L,cmp);
for (int i = 0; i < L; ++i)
{
double num = find(pp[i].s);
printf("%s %.4lf\n",pp[i].s,100.0*num/(1.0*sum));
}
return 0;
}



posted @ 2012-04-06 21:56  E_star  阅读(204)  评论(0编辑  收藏  举报