-
Notifications
You must be signed in to change notification settings - Fork 28
/
Map_Sum_Pairs.cpp
78 lines (69 loc) · 2.41 KB
/
Map_Sum_Pairs.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
class MapSum {
class Trie {
class trieNode {
public:
int value;
int sum;
unordered_map<char, trieNode*> children;
trieNode(): value(0), sum(0) {
children = unordered_map<char, trieNode*>();
}
trieNode(int value): value(value), sum(value) {
children = unordered_map<char, trieNode*>();
}
};
int insert(int indx, string const& key, const int value, trieNode* pCrawl) {
if(indx == key.length() - 1) {
if(pCrawl->children.find(key[indx]) == pCrawl->children.end()) {
pCrawl->children[key[indx]] = new trieNode(value);
return value;
}
int oldValue = pCrawl->children[key[indx]]->value;
pCrawl->children[key[indx]]->value = value;
pCrawl->children[key[indx]]->sum += value;
pCrawl->children[key[indx]]->sum -= oldValue;
return value - oldValue;
}
if(pCrawl->children.find(key[indx]) == pCrawl->children.end()) {
pCrawl->children[key[indx]] = new trieNode();
}
int deltaSum = insert(indx + 1, key, value, pCrawl->children[key[indx]]);
pCrawl->children[key[indx]]->sum += deltaSum;
return deltaSum;
}
trieNode* root;
public:
Trie(): root(new trieNode()) {}
int query(string const& key) {
trieNode* pCrawl = root;
for(int i = 0; i < key.length(); i++) {
if(pCrawl->children.find(key[i]) == pCrawl->children.end()) {
return 0;
}
pCrawl = pCrawl->children[key[i]];
}
return pCrawl->sum;
}
void insert(string const& key, int const value) {
insert(0, key, value, root);
}
};
Trie* trie;
public:
/** Initialize your data structure here. */
MapSum() {
trie = new Trie();
}
void insert(string key, int val) {
trie->insert(key, val);
}
int sum(string prefix) {
return trie->query(prefix);
}
};
/**
* Your MapSum object will be instantiated and called as such:
* MapSum obj = new MapSum();
* obj.insert(key,val);
* int param_2 = obj.sum(prefix);
*/