Skip to content

Instantly share code, notes, and snippets.

@jiunbae
Created September 27, 2015 20:27
Show Gist options
  • Save jiunbae/48995c2f7f9e8723141f to your computer and use it in GitHub Desktop.
Save jiunbae/48995c2f7f9e8723141f to your computer and use it in GitHub Desktop.
template<typename type>
class HeapTree {
private:
type max(type a, type b) { return a > b ? a : b; }
type min(type a, type b) { return a > b ? b : a; }
vector<type> m_ele, M_ele;
size_t e_size, t_size;
pair<type,type> qquery(size_t node, size_t begin, size_t end, size_t first, size_t second)
{
if (end < first || begin > second)
return {-1, -1 };
if (begin >= first && end <= second)
return { this->M_ele.at(node), this->m_ele.at(node) };
pair<type, type> p1 = this->qquery(2 * node, begin, (begin + end) / 2, first, second);
pair<type, type> p2 = this->qquery(2 * node + 1, (begin + end) / 2 + 1, end, first, second);
if (p1.first == -1 && p1.second ==-1)
return p2;
if (p2.first == -1 && p2.second == -1)
return p1;
return { max(max(0,p1.first),max(0,p2.first)), min(max(0,p1.second),max(0,p2.second)) };
}
void uupdate(size_t index, pair<type,type> value)
{
if (index)
{
this->M_ele.at(index) = value.first;
this->m_ele.at(index) = value.second;
size_t pair_index = index % 2 ? index - 1: index + 1;
type val_max = max(this->M_ele.at(index), this->M_ele.at(pair_index));
type val_min = min(this->m_ele.at(index), this->m_ele.at(pair_index));
uupdate(index / 2, { val_max, val_min });
}
return;
}
public:
HeapTree(vector<type> vector)
{
this->e_size = vector.size();
this->t_size = pow(2., (int)log2(this->e_size) + 1);
this->m_ele.assign(this->t_size * 2, 0);
this->M_ele.assign(this->t_size * 2, 0);
for (size_t index = 0; index < this->e_size; index++)
update(index, vector.at(index));
}
void update(size_t index, type value)
{
return this->uupdate(index + this->t_size, {value, value});
}
pair<type, type> query(size_t first, size_t second)
{
return this->qquery(1, 0, this->t_size - 1, first, second);
}
type query(size_t index)
{
return this->m_ele.at(this->t_size + index);
}
~HeapTree()
{ }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment