线段树源码
SegmentTree.h源码
#pragma once
#include "stdafx.h"
class SegmentTreeNode
{
public:
int min;
int max;
double coverWeight;
double containWeight;
SegmentTreeNode* left;
SegmentTreeNode* right;
SegmentTreeNode(int min, int max):left(NULL),right(NULL), coverWeight(0), containWeight(0)
{this->min = min; this->max = max;}
};
class SegmentTree
{
private:
SegmentTreeNode* root;
private:
void add(SegmentTreeNode* node, int min, int max, double weight)
{
if(node->min == min && node->max == max)
{
node->coverWeight += weight;
node->containWeight += (max-min)*weight;
return;
}
node->containWeight += (max-min)*weight;
if(node->min +1 >= node->max)
{
return;
}
int mid = (node->min+node->max)/2;
if(node->left == NULL)
{
node->left = new SegmentTreeNode(node->min,mid);
}
if(node->right == NULL)
{
node->right = new SegmentTreeNode(mid, node->max);
}
if( max <= mid)
{
add(node->left, min,max,weight);
}
else if(min >= mid)
{
add(node->right, min, max, weight);
}
else
{
add(node->left, min, mid, weight);
add(node->right, mid, max, weight);
}
}
double getWeight(SegmentTreeNode* node, int min, int max)
{
if(node == NULL)
{
return 0;
}
if(node->min == min && node->max == max)
{
return node->containWeight;
}
double w = node->coverWeight*(max-min);
int mid = (node->min+node->max)/2;
if(max <= mid)
{
w += getWeight(node->left,min, max);
}
else if( min >= mid)
{
w += getWeight(node->right,min,max);
}
else
{
w += getWeight(node->left,min, mid) + getWeight(node->right,mid,max);
}
return w;
}
void destroy(SegmentTreeNode* node)
{
if(node == NULL)
{
return;
}
destroy(node->left);
destroy(node->right);
delete node;
}
public:
SegmentTree(int min, int max)
{
root = new SegmentTreeNode(min,max);
}
~SegmentTree()
{
if(root!= NULL)
{
destroy(root);
root = NULL;
}
}
void add(int min, int max, double weight=1)
{
add(root, min,max,weight);
}
double getWeight(int min, int max)
{
return getWeight(root, min, max);
}
};
SegmentTreeTest.h源码
#pragma once
#include "stdafx.h"
#include "SegmentTree.h"
#include <iostream>
using namespace std;
class SegmentTreeTest
{
public:
void doTest()
{
SegmentTree* segmentTree = new SegmentTree(-10,10);
segmentTree->add(-3,5,1);
segmentTree->add(-5,10,3);
segmentTree->add(3,7,5);
double weight = segmentTree->getWeight(-1,5);
cout << weight;
}
};