最近在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);
}
}