POJ 2418 解题报告

这道题我是用trie过的,比较轻松。输出是用DFS。值得注意的一点是排序直接用ascii,所以每个trie节点都包含128个ascii字符(因为有非空格字母字符存在)。

thestoryofsnow2418Accepted1512K641MSC++
/* 
ID: thestor1 
LANG: C++ 
TASK: poj2418 
*/
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <limits>
#include <string>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <cassert>

using namespace std;

const int MAXM = 31;

// whitespace, a ~ z and A ~ Z
// screw it, use all ascii characters
const int NCHILD = 128;

class Trie
{
public:	
	Trie *next[NCHILD];
	int cnt;
	Trie() 
	{
		for (int i = 0; i < NCHILD; ++i)
		{
			next[i] = NULL;
		}
		cnt = 0;
	}
};

int char2index(int ch)
{
	return ch;
	// int c = -1;
	// if (ch == ' ')
	// {
	// 	c = 0;
	// }
	// else
	// {

	// 	if ('a' <= ch && ch <= 'z')
	// 	{
	// 		// 1 ~ 26
	// 		c = ch - 'a' + 1;	
	// 	}
	// 	else
	// 	{
	// 			// should be all uppercase now.
	// 		assert('A' <= ch && ch <= 'Z');
	// 			// 27  + 0 ~ 27 + 25
	// 		c = ch - 'A' + 27;
	// 	}
	// }
	// return c;
}

char index2char(int index)
{
	return index;
	// char ch;
	// if (index == 0)
	// {
	// 	ch = ' ';
	// }
	// else if (1 <= index && index <= 26)
	// {
	// 	ch = 'a' + index - 1;
	// }
	// else
	// {
	// 	assert (27 <= index && index < NCHILD);
	// 	ch = 'A' + index - 27;
	// }
	// return ch;
}

void insertTrie(Trie *trie, char name[])
{
	Trie *p = trie;
	int c;
	for (int i = 0; name[i] != '\0' && name[i] != '\n'; ++i)
	{
		c = char2index(name[i]);

		if (p->next[c] == NULL)
		{
			p->next[c] = new Trie();
		}

		p = p->next[c];
	}

	p->cnt++;
}

void printTrie(Trie *trie, const int N, char name[], int len)
{
	if (trie->cnt > 0)
	{
		name[len] = '\0';
		printf("%s %.4lf\n", name, trie->cnt * 100.0 / N);
	}

	for (int c = 0; c < NCHILD; ++c)
	{
		if (trie->next[c] != NULL)
		{
			name[len] = index2char(c);
			printTrie(trie->next[c], N, name, len + 1);
		}
	}
}

int main()
{
	char name[MAXM];
	Trie *trie = new Trie();
	int N = 0;
	while(fgets(name, MAXM, stdin) > 0)
	{
		// printf("name:[%s]\n", name);
		insertTrie(trie, name);
		N++;
	}

	// printf("N: %d\n", N);

	printTrie(trie, N, name, 0);

	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值