This repository has been archived by the owner on Feb 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Partial_Persistence.cpp
62 lines (62 loc) · 1.68 KB
/
Partial_Persistence.cpp
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
#include <iostream>
#include <vector>
using namespace std;
class PartiallyPersistentArray {
private:
int n;
int versions;
vector<vector<int>> data;
vector<int> lastModified;
public:
PartiallyPersistentArray(int size, int numVersions) : n(size), versions(numVersions + 1) {
data.resize(versions, vector<int>(n, 0));
lastModified.resize(n, -1);
}
void update(int version, int index, int value) {
if (version < 0 || version >= versions) {
cout << "Invalid version" << endl;
return;
}
data[version][index] = value;
lastModified[index] = version;
}
int query(int version, int index) {
if (version < 0 || version >= versions) {
cout << "Invalid version" << endl;
return -1;
}
int result = 0;
for (int i = lastModified[index]; i >= 0; --i) {
result = data[i][index];
if (i == version) {
break;
}
}
return result;
}
};
int main() {
int n = 5;
int numVersions = 3;
PartiallyPersistentArray ppa(n, numVersions);
ppa.update(0, 2, 5);
ppa.update(0, 4, 8);
ppa.update(1, 1, 3);
ppa.update(1, 3, 7);
cout << "Querying array at version 0:" << endl;
for (int i = 0; i < n; ++i) {
cout << ppa.query(0, i) << " ";
}
cout << endl;
cout << "Querying array at version 1:" << endl;
for (int i = 0; i < n; ++i) {
cout << ppa.query(1, i) << " ";
}
cout << endl;
cout << "Querying array at version 2:" << endl;
for (int i = 0; i < n; ++i) {
cout << ppa.query(2, i) << " ";
}
cout << endl;
return 0;
}