スプレイツリーをコーディングしました。ノードはこのように表されます。
struct Node{
Node *l; /// The left Node
Node *r; /// The right Node
int v; /// The Value
};
ここで、特定の範囲内のツリー内のすべての数値の合計を知る必要があります。このために、次の名前の関数を実装しましたsummation.
void summation(Node *R, int st, int ed)
{
if(!R) return;
if(R->v < st){ /// should not call left side
summation(R->r, st, ed);
}
else if(R->v > ed){ /// should not call right side
summation(R->l, st, ed);
}
else{ /// should call both side
ret+=R->v;
summation(R->l, st, ed);
summation(R->r, st, ed);
}
return;
}
ret
関数を呼び出す前に初期化されるグローバルint
変数です。2 つのパラメーター&は範囲 (包括的) を定義します。0
summation
st
ed
このsummation
関数は、O(n) の複雑さで機能します。誰でもこれのより速い実装を提案できますか??