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

题型:综合题,各种方法解决。


分析:

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

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


代码:

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值