您可以使用具有如下节点的自平衡树:
public class Node
{
public Node(Node leftChild, Node rightChild)
{
FirstPoint = leftChild.FirstPoint;
LastPoint = rightChild.LastPoint;
LeafCount = leftChild.LeafCount + rightChild.LeafCount;
BetweenDistance = leftChild.LastPoint.DistanceTo(rightChild.FirstPoint);
TotalDistanceSum = leftChild.TotalDistanceSum
+ BetweenDistance
+ rightChild.TotalDistanceSum;
IsLeaf = false;
LeftChild = leftChild;
RightChild = rightChild;
}
public Node(Point p)
{
FirstPoint = p;
LastPoint = p;
LeafCount = 1;
IsLeaf = true;
}
/// The point of the leftmost decendant.
public Point FirstPoint { get; set; }
/// The point of the rightmost decendant.
public Point LastPoint { get; set; }
/// Number of leaves.
public int LeafCount { get; set; }
/// The distance from FirstPoint to LastPoint along the path.
public double TotalDistanceSum { get; set; }
/// The distance between LeftChild and RightChild.
public double BetweenDistance { get; set; }
/// Flag wheter this is a node or a leaf.
public bool IsLeaf { get; set; }
/// Left child of this non-leaf node.
public Node LeftChild { get; set; }
/// Right child of this non-leaf node.
public Node RightChild { get; set; }
/// Calculates the distance between two point along the path. 'start' is inclusive. 'end' is exclusive.
public double DistanceSum(int start, int end)
{
if (IsLeaf || start >= LeafCount || end < 0 || start >= end)
return 0;
if (end > LeafCount) end = LeafCount;
if (start < 0) start = 0;
if (start == 0 && end == LeafCount)
return TotalDistanceSum;
int n = LeftChild.LeafCount;
return LeftChild.DistanceSum(start, end)
+ BetweenDistance
+ RightChild.DistanceSum(start - n, end - n);
}
}
public class Point
{
public double X { get; private set; }
public double Y { get; private set; }
public Point(double x, double y)
{
X = x;
Y = y;
}
public double DistanceTo(Point other)
{
double dx = other.X - X;
double dy = other.Y - Y;
return Math.Sqrt(dx*dx + dy*dy);
}
}
例子:
var tree = new Node(
new Node(
new Node(new Point(0,0)),
new Node(new Point(1,0))
),
new Node(
new Node(new Point(1,1)),
new Node(new Point(0,1))
)
);
double dist = tree.DistanceSum(0,4); // returns 3.0