算法与数据结构第八次作业 count2

来源:互联网 发布:2017程序员考试真题 编辑:程序博客网 时间:2024/05/16 20:50


这次的题数据量很大,用hash也超时了,刚好学到字典,用了二叉搜索树。

主要思路是:

1.把要插入的第一个数字初始化为树根。
2.每插入一个数字之前,把rank初始化为1。
3.比当前结点小,往左走,同时当前结点的左子树数字个数加一。
4.比当前结点大,往右走,同时把当前结点的自身数字个数和左子树数字个数加到rank。
5.等于当前结点,当前结点自身数字个数加一。
6.走到底,说明树里没有这个数字,新建结点,结点的自身数字个数、左子树数字个数分别初始化为1、0。
7.插入结束时,rank即为大小排名。

代码:

#include <stdio.h>#include <malloc.h>#define LL __int64struct node{LL num;int selfcnt;int leftcnt;node *left;node *right;}*head,*p;int len=sizeof(node);node *newnode(LL t){node *p=(node *)malloc(len);p->num=t;p->selfcnt=1;p->leftcnt=0;p->left=0;p->right=0;return p;}int n,rank,i;LL t;int main(){scanf("%d",&n);scanf("%I64d",&t);printf("1\n");head=newnode(t);for(i=1;i<n;i++){scanf("%I64d",&t);p=head;rank=1;while(1){if(t==p->num){p->selfcnt++;rank+=p->leftcnt;break;}else if(t<p->num){p->leftcnt++;if(p->left!=0){p=p->left;}else{p->left=newnode(t);break;}}else{rank+=p->leftcnt+p->selfcnt;if(p->right!=0)p=p->right;else{p->right=newnode(t);break;}}}printf("%d\n",rank);}return 0;}


用这种方法,最后一个测试点还是过不了,看了一下全过的优秀代码,用到了树状数组这种高级数据结构,之后看懂了再贴上来。

0 0
原创粉丝点击