您的位置:首页 > 其它

POJ_2418_Hardwood Species(map实现、Trie tree实现)

2014-04-24 14:00 459 查看
题型:综合题,各种方法解决。

分析:

感觉这是一个强大的题目,可以用各种高难度数据结构解决。

思想很简单,就不多说了。

代码:

map实现:

#include <iostream>
#include <string>
#include <map>
#include <iterator>
#include <cstdio>
using namespace std;
int main(){
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
string s;
int cnt = 0;
map<string,int> tree;
while(getline(cin,s)!=NULL){
tree[s]++;
cnt++;
}
map<string,int>::iterator iter;
for(iter = tree.begin();iter != tree.end();iter++){
cout<<iter->first;
printf(" %.4f\n",iter->second*100.0/cnt);
}
return 0;
}


Trie tree实现:

#include<iostream>
#include<cmath>
#include<cstdio>
#include<cstring>
#define MAXN 130
using namespace std;

struct Node{
char name[35];
int num;
bool tree;
Node *next[MAXN];
Node(){
num = 0;
tree = false;
for(int i=0;i<MAXN;i++){
next[i] = NULL;
}
}
};

int sum;

void insert(Node *root,char *str){
int len = strlen(str);

Node *q;
q = root;

for(int i=0;i<len;i++){
int x = str[i];
if(q->next[x] == NULL){
q->next[x] = new Node;
}
q = q->next[x];
}
q->num++;
q->tree = true;
strcpy(q->name,str);
}

void output(Node *root){
Node *q;
q = root;

if(q->tree){
printf("%s %.4f\n",q->name,q->num*100.00/sum);
}

for(int i=0;i<MAXN;i++){
if(q->next[i] != NULL){
//	q = q->next[i];
output(q->next[i]);
}
}
}

int main(){
//freopen("in.txt","w",stdin);
//freopen("out.txt","r",stdout);
Node *root = new Node;
sum = 0;
char str[35];
while(gets(str) != 0){
insert(root,str);
//cout<<"****"<<str<<endl;
sum++;
}

output(root);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: