summaryrefslogtreecommitdiff
path: root/extractor/veb_tree.cc
blob: f89454458001646e1d3318202089054a9f75906a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <cmath>

#include "veb_tree.h"

VEBTree::VEBTree(int size) {
  int num_bits = ceil(log2(size));

  lower_bits = num_bits >> 1;
  upper_size = (size >> lower_bits) + 1;

  clusters.reserve(upper_size);
  clusters.resize(upper_size);
}

int VEBTree::GetNextValue(int value) {
  return value & ((1 << lower_bits) - 1);
}

int VEBTree::GetCluster(int value) {
  return value >> lower_bits;
}

int VEBTree::Compose(int cluster, int value) {
  return (cluster << lower_bits) + value;
}

void VEBTree::Insert(int value) {
  if (min == -1 && max == -1) {
    min = max = value;
    return;
  }

  if (value < min) {
    swap(min, value);
  }

  int cluster = GetCluster(value), next_value = GetNextValue(value);
  if (clusters[cluster] == NULL) {
    clusters[cluster] = VEB::Create(1 << lower_bits);
    if (summary == NULL) {
      summary = VEB::Create(upper_size);
    }
    summary->Insert(cluster);
  }
  clusters[cluster]->Insert(next_value);

  if (value > max) {
    max = value;
  }
}

int VEBTree::GetSuccessor(int value) {
  if (value >= max) {
    return -1;
  }
  if (value < min) {
    return min;
  }

  int cluster = GetCluster(value), next_value = GetNextValue(value);
  if (clusters[cluster] != NULL &&
      next_value < clusters[cluster]->GetMaximum()) {
    return Compose(cluster, clusters[cluster]->GetSuccessor(next_value));
  } else {
    int next_cluster = summary->GetSuccessor(cluster);
    if (next_cluster == -1) {
      return -1;
    }
    return Compose(next_cluster, clusters[next_cluster]->GetMinimum());
  }
}