本题可以有多种解决方法,采用STL map 或者 HASH 或者 二叉查找树 均可
//============================================================================
// Name : POJ_2418_map.cpp
// Author : tiger
// Version :
// Copyright : Your copyright notice
// Description : AC_1594MS_380K
//============================================================================
#include <iostream>
#include <map>
#include <string>
//#include <stdio.h>
using namespace std;
int main() {
freopen("in","r",stdin);
map<string,int> mymap;
map<string,int>::iterator it;
string str;
char s[50];
mymap.clear();
int sum = 0;
while(gets(s) && s[0] != 0)
{
str = s;
mymap[str] ++;
sum++;
}
for(it = mymap.begin(); it != mymap.end(); it ++)
{
cout << it->first;
printf(" %.4f/n",(double)(it->second)*100.0/ (double)sum);
//printf("%s %0.4f/n",it->first,(double)(it->second)/ (double)sum);
}
return 0;
}
//============================================================================
// Name : POJ_2418_hash.cpp
// Author : tiger
// Version :
// Copyright : 利用hash表
// Description : AC_844MS_708K
//============================================================================
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
struct NODE
{
char str[32];
int num;
NODE *next;
};
struct HASH
{
NODE *next;
} h[10005];
unsigned int BKDRHash(char *str)
{
unsigned int seed = 131; // 31 131 1313 13131 131313 etc..
unsigned int hash = 0;
while (*str)
{
hash = hash * seed + (*str++);
}
return (hash & 0x7FFFFFFF);
}
void insert(char *s)
{
unsigned int hash = BKDRHash(s) % 10001;
if (h[hash].next == NULL)//桶为空
{
NODE *temp = new NODE;
temp->next = NULL;
temp->num = 1;
strcpy(temp->str, s);
h[hash].next = temp;
}
else//桶不空
{
//在桶中查找相同节点
NODE *p = h[hash].next;
if(strcmp(p->str,s) == 0)
{
p->num++;
return;
}
while(p->next)
{
p = p->next;
if(strcmp(p->str,s) == 0)
{
p->num++;
return;
}
}
//往桶中添加新节点
NODE *temp = new NODE;
temp->next = NULL;
temp->num = 1;
strcpy(temp->str, s);
p->next = temp;
return;
}
}
struct treenode
{
char str[32];
int num;
};
bool cmp(treenode a,treenode b)
{
if(strcmp(a.str,b.str)<=0)
return true;
return false;
}
int main()
{
freopen("in", "r", stdin);
memset(h, 0, sizeof(h));
char s[32];
double sum= 0;
int i,j;
struct treenode tree[10001];
while (gets(s) && s[0] != 0)
{
insert(s);
sum++;
}
//从hash表中取出所有元素,保存到tree中,然后排序
NODE *p;
for(i=0,j = 0; i < 10001;i++)
{
p = h[i].next;
while(p)
{
strcpy(tree[j].str,p->str);
tree[j].num = p->num;
j++;
p = p->next;
}
}
sort(tree,tree+j,cmp);
for(i =0; i < j; i++)
{
printf("%s %.4f/n",tree[i].str,(double)(tree[i].num) * 100.0 / sum);
}
return 0;
}