最近在pku.acm上做了道题..一个挺好的题... 是对大约1百万条信息进行处理的题目:我用的是二叉查找树,代码如下:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<assert.h>
using namespace std;
typedef struct node
{
char key[30];
double num;
struct node *lchild, *rchild;
}tree_node, *tree_ptr;
int totalNum = 1;
tree_ptr head = NULL;
void InsertNode(char* str_ptr);
void Print(tree_ptr head);
int main(void)
{
char key[30];
head = (tree_ptr)malloc(sizeof(tree_node));
head->lchild = NULL;
head->rchild = NULL;
head->num = 1;
gets(head->key);
while(gets(key) != 0)
{
totalNum++;
InsertNode(key);
}
Print(head);
return 0;
}
void InsertNode(char* str_ptr)
{
tree_ptr tryNode,ptryNode, _inode;
tryNode = head;
int temp = 0;
while(NULL != tryNode)
{
ptryNode = tryNode;
temp = strcmp(tryNode->key, str_ptr);
if (temp == 0)
{
tryNode->num++;
return;
}
else
{
if (temp < 0)
{
tryNode = tryNode->rchild;
continue;
}
else if (temp > 0)
{
tryNode = tryNode->lchild;
continue;
}
}
}
_inode = (tree_ptr)malloc(sizeof(tree_node));
_inode->lchild = NULL;
_inode->rchild = NULL;
_inode->num = 1;
strcpy(_inode->key, str_ptr);
if (temp < 0)
{
ptryNode->rchild = _inode;
}
else
{
ptryNode->lchild = _inode;
}
}
void Print(tree_ptr head)
{
if (NULL != head)
{
Print(head->lchild);
printf("%s %.4f ",head->key, (head->num * 100) / totalNum);
Print(head->rchild);
}
}
#include<cstdio>
#include<cstdlib>
#include<assert.h>
using namespace std;
typedef struct node
{
char key[30];
double num;
struct node *lchild, *rchild;
}tree_node, *tree_ptr;
int totalNum = 1;
tree_ptr head = NULL;
void InsertNode(char* str_ptr);
void Print(tree_ptr head);
int main(void)
{
char key[30];
head = (tree_ptr)malloc(sizeof(tree_node));
head->lchild = NULL;
head->rchild = NULL;
head->num = 1;
gets(head->key);
while(gets(key) != 0)
{
totalNum++;
InsertNode(key);
}
Print(head);
return 0;
}
void InsertNode(char* str_ptr)
{
tree_ptr tryNode,ptryNode, _inode;
tryNode = head;
int temp = 0;
while(NULL != tryNode)
{
ptryNode = tryNode;
temp = strcmp(tryNode->key, str_ptr);
if (temp == 0)
{
tryNode->num++;
return;
}
else
{
if (temp < 0)
{
tryNode = tryNode->rchild;
continue;
}
else if (temp > 0)
{
tryNode = tryNode->lchild;
continue;
}
}
}
_inode = (tree_ptr)malloc(sizeof(tree_node));
_inode->lchild = NULL;
_inode->rchild = NULL;
_inode->num = 1;
strcpy(_inode->key, str_ptr);
if (temp < 0)
{
ptryNode->rchild = _inode;
}
else
{
ptryNode->lchild = _inode;
}
}
void Print(tree_ptr head)
{
if (NULL != head)
{
Print(head->lchild);
printf("%s %.4f ",head->key, (head->num * 100) / totalNum);
Print(head->rchild);
}
}
本文介绍了一种使用二叉查找树处理大量数据的方法。通过插入节点并统计重复项,最终输出每个唯一项及其出现频率。代码实现了二叉查找树的基本操作,包括插入和遍历。
4718

被折叠的 条评论
为什么被折叠?



