-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathinverse_vector.h
46 lines (37 loc) · 1.07 KB
/
inverse_vector.h
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
#ifndef INVERSE_VECTOR_H
#define INVERSE_VECTOR_H
#include <cassert>
#include <algorithm>
#include <vector>
//
// The inverse vector p of a vector v is a vector such that the elements
// v[p[i]], v[p[i]+1], v[p[i]+2], ..., v[p[i+1]-1] are exactly the elements
// with value i in v. If i does not occur in v, then p[i] == p[i+1]. v must be
// a sorted vector of unsigned integers.
//
inline
std::vector<unsigned>invert_vector(const std::vector<unsigned>&v, unsigned element_count){
std::vector<unsigned>index(element_count+1);
if(v.empty()){
std::fill(index.begin(), index.end(), 0);
}else{
index[0] = 0;
unsigned pos = 0;
for(unsigned i=0; i<element_count; ++i){
while(pos < v.size() && v[pos] < i)
++pos;
index[i] = pos;
}
index[element_count] = v.size();
}
return index;
}
inline
std::vector<unsigned>invert_inverse_vector(const std::vector<unsigned>&sorted_index){
std::vector<unsigned>v(sorted_index.back());
for(unsigned i=0; i<sorted_index.size()-1; ++i)
for(unsigned j=sorted_index[i]; j<sorted_index[i+1]; ++j)
v[j] = i;
return v;
}
#endif