北大ACM上的2418题解法

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值