BST--二叉搜索树的美妙性质。。。。 ( SPOJ 3544 )

题目:http://acdreamoj.sinaapp.com/problem.php?id=1156

  Also see @ http://www.spoj.pl/problems/BST/

大意:求bst插入的数的层数之和。

思考:暴力模拟可达O(n^2)。。。300000 ,1,2,3。。。300000必挂

看了标程想了半天,终于在去领快递(数论概论)的路上想通了。。。

用区间来想,bst每个分支处都是限定了一个区间(l,r),新插入的数x所在区间即为(小于x且最接近x的数L,大于x且最接近的数R),因此x的父亲就是L和R中较深的那个,因此depth(x)=Max(depth(L),depth(R))+1。。。

用map::lower_bound()来找L和R,总复杂度O(n*logn)


标程:

#include <algorithm>
#include <cstdio>
#include <map>
using namespace std;
  
int main() {
   int n; scanf("%d", &n);
  
   map<int, int> depth;
   long long zbr = 0;
   for ( int i=0; i<n; ++i ) {
      int X; scanf("%d", &X);
      int d = 0;
      map<int, int>::iterator it = depth.lower_bound(X);
      if ( it != depth.end()   ) d = max(d, it->second+1);
      if ( it != depth.begin() ) d = max(d, (--it)->second+1);
      depth[X] = d;
      zbr += d;
      printf("%lld\n", zbr);
   }
     
   return 0;
}
posted @ 2012-04-21 13:59  lxc902  阅读(241)  评论(0编辑  收藏  举报