RMQ--线段树实现

线段树保存当前节点的最大(小)值,未经编译,仅供参考

#define MAX 0xfffffff
#define MIN -0xfffffff
struct Node {
  Node():left_(NULL), right_(NULL), head_(0), tail_(0), min_(0), max_(0) {}
  Node* left_;
  Node* right_;
  int head_;
  int tail_;
  int min_;
  int max_;
};

class SegmentTree {
 public:
  SegmentTree(vector<int> values) : root_(NULL), values_(values) {}

  void Init() {
    root_ = BuildInternal(0, values_.size() - 1);
  }

  int FindMax(int m, int n) { 
   return FindMax(root_, m, n); 
  }

  int FindMin(int m, int n) {
    return FindMin(root_, m, n); 
  }
 private:
  int FindMax(Node* node, int m, int n) {
    if (!node) return MIN;
    if (m > node->right_ || n < node->left_) return MIN;
    if (m <= node->head_ && n >= node->tail_) {
      return node->max_;
    }   
    return max(FindMax(node->left_, m, n), FindMax(node->right_, m, n));
  }

  int FindMin(Node* node, int m, int n) {
    if (!node) return MAX;
    if (m > node->right_ || n < node->left_) return MAX;
    if (m <= node->head_ && n >= node->tail_) {
      return node->min_;
    }   
    return min(FindMin(node->left_, m, n), FindMin(node->right_, m, n));
  }

  Node* BuildInternal(int head, int tail) {
    if (head > tail) return NULL;
    Node* root = new Node();
    root->head_ = head;
    root->tail_ = tail;
    if (head == tail) {
      root->min_ = values_[head];
      root->max_ = values_[head];
      return root;
    }   
    Node* left = BuildInternal(head, (head + tail) / 2);
    Node* right = BuildInternal((head + tail) / 2 + 1, tail);
    root->left_ = left;
    root->right_ = right;
    if (!root->left_) {
      root->min_ = root->right_->min_;
      root->max_ = root->right_->max_;
      return root;
    }
    if (!root->right_) {
      root->min_ = root->left_->min_;
      root->max_ = root->left_->max_;
      return root;
    }
    root->min_ = min(root->left->min_, root->right_->min_);
    root->max_ = min(root->left->max_, root->right_->max_);
    return root;
  }

 private:
  Node* root_;
  vector<int> values_;
};
}

 

posted @ 2013-08-22 15:44  dmthinker  阅读(106)  评论(0)    收藏  举报