You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
We can use an ordered set to store the attractions, and a variable $i$ to record the current number of queries, initially $i = -1$.
83
+
84
+
When calling the `add` method, we take the negative of the attraction's rating, so that we can use the ordered set to sort by rating in descending order. If the ratings are the same, sort by the dictionary order of the attraction names in ascending order.
85
+
86
+
When calling the `get` method, we increment $i$ by one, and then return the name of the $i$-th attraction in the ordered set.
87
+
88
+
The time complexity of each operation is $O(\log n)$, where $n$ is the number of added attractions. The space complexity is $O(n)$.
89
+
90
+
<!-- tabs:start -->
91
+
92
+
```python
93
+
from sortedcontainers import SortedList
94
+
95
+
96
+
classSORTracker:
97
+
98
+
def__init__(self):
99
+
self.sl = SortedList()
100
+
self.i =-1
101
+
102
+
defadd(self, name: str, score: int) -> None:
103
+
self.sl.add((-score, name))
104
+
105
+
defget(self) -> str:
106
+
self.i +=1
107
+
returnself.sl[self.i][1]
108
+
109
+
110
+
# Your SORTracker object will be instantiated and called as such:
111
+
# obj = SORTracker()
112
+
# obj.add(name,score)
113
+
# param_2 = obj.get()
114
+
```
115
+
116
+
```cpp
117
+
#include<ext/pb_ds/assoc_container.hpp>
118
+
#include<ext/pb_ds/hash_policy.hpp>
119
+
usingnamespace__gnu_pbds;
120
+
121
+
template <classT>
122
+
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
123
+
124
+
classSORTracker {
125
+
public:
126
+
SORTracker() {
127
+
}
128
+
129
+
void add(string name, int score) {
130
+
st.insert({-score, name});
131
+
}
132
+
133
+
string get() {
134
+
return st.find_by_order(++i)->second;
135
+
}
136
+
137
+
private:
138
+
ordered_set<pair<int, string>> st;
139
+
int i = -1;
140
+
};
141
+
142
+
/**
143
+
* Your SORTracker object will be instantiated and called as such:
We notice that the query operations in this problem are performed in strictly increasing order. Therefore, we can use a method similar to the median in the data stream. We define two priority queues `good` and `bad`. `good` is a min-heap, storing the current best attractions, and `bad` is a max-heap, storing the current $i$-th best attraction.
155
+
156
+
Each time the `add` method is called, we add the attraction's rating and name to `good`, and then add the worst attraction in `good` to `bad`.
157
+
158
+
Each time the `get` method is called, we add the best attraction in `bad` to `good`, and then return the worst attraction in `good`.
159
+
160
+
The time complexity of each operation is $O(\log n)$, where $n$ is the number of added attractions. The space complexity is $O(n)$.
0 commit comments