We need to process a sequence of n operations of three types: add (1), remove (2), query (3). But they are not applied in the order given; each operation occurs at a specific distinct time ti, and we have to consider the state of the multiset at that moment when performing the operation. However, the operations themselves are performed in the order of input (i.e., Artem's actions in his "time-travel" sequence). But note: The problem statement: "Artem doesn't simply apply operations to the multiset one by one, he now travels to different moments of time and apply his operation there." So the input sequence is the order in which Artem performs his actions (time travels). Each action has a time ti when it is applied in the "multiset timeline". Since times are distinct, we can think of each operation being applied at its ti. The state of the multiset at any time t is determined by all operations with time <= t that have been performed (in the order of Artem's actions? Actually careful: The multiset evolves over the timeline. Artem is applying operations at specific times. The operations themselves are applied in the order of his travels, but the effect of each operation is placed at its designated time ti. However, because he can travel to different times, later in his action sequence he might insert an operation at a time earlier than some previous operations. This changes the timeline and may affect the result of queries that were already made? But the problem says: "The answer to the query of the third type is computed at the moment Artem makes the corresponding query and are not affected in any way by future changes he makes." That suggests that when we process the input sequentially, we need to compute the answer for each query based on the state of the timeline as it exists at that moment (considering all operations that have been "applied" so far, with their times). However, after we compute the query, later operations may add or remove elements at times that could potentially affect the answer if we considered them, but the answer we output is fixed at that moment (so we output based on the timeline as it stands when the query is made). This is similar to a classic problem: offline processing of operations that are inserted at specific times, with queries asking for the count at a specific time, and operations can be added out of time order. Since n up to 100k, and ti, xi up to 1e9.
We need to support:
- Insert an "add" at time t for value x.
- Insert a "remove" at time t for value x (removing one occurrence, guaranteed that there is at least one occurrence of x at that exact time? Actually the guarantee: "after each operation is applied all operations of the first and second types are consistent." That is, whenever a remove is performed, we ensure that there is at least one instance of x present in the multiset at that moment (i.e., when we apply that operation at time t, the state of multiset at time t (taking into account all previously applied operations that affect times <= t) must have at least one x to remove). Similarly, adds are always fine. So we need to maintain that condition as we apply operations. But we are told that the input is valid, i.e., if we process operations in input order, and apply them to the timeline (with times), then before each remove, the count of x at that time is >=1. So we don't need to validate; we just need to process them.
Goal: For each query of type 3 (ask), output the count of x at time t, based on the timeline as constructed by all operations processed so far (including earlier operations that may have later times, and also later times? But only operations processed so far. Since we process sequentially, at step i we have a set of operations O_i = { first i operations }. Then for query i, we need to answer the count of x at time t, based on O_i. And subsequent operations (j>i) are not considered. So it's like we have an online sequence of updates (at given times) and queries (at given times), and we need to output answers on the fly. However, updates are not ordered by time; they can be at arbitrary times. Queries ask for the count at a specific time.
We can think of each value x independently. For each x, we have a set of events: add (+1) at time t, remove (-1) at time t. Queries ask for the prefix sum up to time t (i.e., number of adds minus removes with time <= t) for that x. However, note that removals are only allowed if at that moment there is at least one instance. In terms of counting, it's just the cumulative sum of events up to time t. But careful: The remove operation at time t removes one instance that exists at that time; effectively it's a -1 event at time t. So the net count at time t (right after applying operations at that exact time? Actually queries ask "at moment t". Usually it means after all operations that happen at time t? Since times are distinct, there is exactly one operation at each time (maybe?). The problem says: "moments of time are distinct". So each operation occurs at a unique time. So at a given time t, there will be at most one operation. Queries also have their own time. So if a query occurs at time t, we need the state after applying all operations with time <= t. But what about an operation that also occurs at time t? Since times are distinct, if a query is at time t, there is no other operation at exactly t (except this query itself). So the state at time t is determined by all adds/removes with times < t. However, if we have an add at time 1 and a remove at time 3, and query at time 3: we should consider remove at time 3? But query at time 3: Since the time of query is 3, and remove is also at time 3. But times are distinct, so query cannot have same time as an update. So safe: we need to consider events with time <= query.t? Since all times are distinct, we can define that state at time t includes all operations with time < t (or maybe <= t? But because query is at time t, and there is no other operation at that same t (except possibly the query itself), it doesn't matter; we can treat it as inclusive of events with time <= t? But if a remove at time t, query at time t+something, they are distinct. So inclusive/exclusive isn't an issue because we can treat queries as needing sum over events with time < query.t. However, there is nuance: In the example, they had:
- Add 5 at time 1.
- Add 5 at time 5? Actually first input example:
1 1 5
3 5 5
1 2 5
3 6 5
2 3 5
3 7 5
Wait let's parse:
- 1 1 5 => add 5 at time 1
- 3 5 5 => query at time 5: output 1
- 1 2 5 => add 5 at time 2
- 3 6 5 => query at time 6: output 2
- 2 3 5 => remove 5 at time 3
- 3 7 5 => query at time 7: output 1
So let's compute: After operations 1-4, we have adds at times 1 and 2. At time 5, count of 5 should be number of adds with time <=5 minus removes with time <=5. No removes yet, so count=2? But they output 1 for query at time 5. Wait they output 1 for the first query. Hmm they have query at time 5 after only first add? But operation order: after 1) add at time 1, then 2) query at time 5: answer 1. So they consider only the add at time 1 because the add at time 2 hasn't been applied yet? But the add at time 2 is later in the input order. At the moment of query (input step 2), the operations applied so far are: add at time 1. The add at time 2 hasn't been performed yet. So the timeline only contains the add at time 1. So the count at time 5 based on that timeline is 1. That's correct: queries are answered based on the set of operations performed up to that point (in input order). So indeed the timeline evolves as we apply operations sequentially, even though they have associated times, the order of application is the input order. So it's like we are building a set of events (time, delta) over time. Each new operation adds an event at its given time. Then for a query we ask: what is the sum of deltas (for that x) for events with time <= query.t, among the events that have been added so far.
Thus it's a classic problem: we need to support two types of operations online:
- Insert an event (t, +1) for a given x.
- Insert an event (t, -1) for a given x.
- Query for a given x and t: sum of deltas for that x with time <= t.
But note that remove operations are guaranteed to be valid: that means that at the moment of insertion of the remove event, the count of x at time t (based on current events) must be >=1. However, we don't need to enforce; it's given.
We need to answer queries online with n up to 100k, times up to 1e9, x up to 1e9.
We can treat each distinct x separately and maintain a data structure for events of that x. Since there can be many distinct x, we need a structure that can handle up to 100k operations across many keys.
A common approach: offline coordinate compression on times and values, and use a Fenwick tree or segment tree over time, but queries are online and we need to consider each x separately? Actually we can treat each operation as (x, t, type). For each x, we need to support dynamic insertion of points and prefix sum queries over time. Since operations are interleaved, we could use a BIT over time but the events are specific to x. However, we could treat the problem as a 2D problem: each add/remove is a point (x, t) with value +1/-1. Query asks: sum over all points with x = given x and t <= query.t. Since x is large, we can compress x values. And we need to support online point updates (adding a value to (x,t)) and queries: sum over a rectangle: x fixed, t <= T. That's like a dynamic BIT of BITs or a Fenwick tree on x of ordered structures on t, but online and n=100k, we can use a Fenwick tree on x with internal balanced BST (e.g., std::set with order statistics) or using a BIT of vectors and offline coordinate compression on t per x? However, updates and queries are interleaved; but we could offline all operations to gather all t for each x? Actually we can process online using a map from x to a Fenwick tree (or order statistic tree) that supports prefix sums on t. But t values are up to 1e9 and per x we have variable number of events (could be up to n). For each x, we could maintain a Fenwick tree over compressed times (the times that appear for that x). Since we process online, we don't know all times for a given x in advance. But we could use a balanced BST that supports order statistics and prefix sums, like a Treap or BIT with dynamic indexing? Or we can use a Fenwick tree with coordinate compression per x by pre-processing all operations offline: we know all operations (updates and queries) in advance (since input is given all at once? But the problem is interactive? No, we read all input; we can process offline. However, note: the queries need to be answered based on the state after previous updates only. But if we have all operations ahead of time, we can process them in order but we can still do offline coordination: we can for each x collect all times that will ever be used in updates or queries? But queries do not modify the structure; they just ask for sum. If we process offline, we could simulate the operations in order while using a data structure that has been built with all future update times known? That might be possible if we pre-collect all times for each x for updates (add/remove) and use a BIT with point updates and prefix queries. However, we need to ensure that when we insert an update at time t, we only affect queries that occur later in input order. That's fine. If we pre-build BITs per x with all possible times (all update times for that x) we can process online easily: for each update, we update BIT at that time by +1 or -1; for each query, we query prefix sum up to time t. That would work because we know all update times for that x in advance (since we have entire input). But note: queries themselves do not provide new times for updates. So we can indeed parse the entire input first, for each x collect all times where an add or remove occurs. Then for each x, we can sort those times and assign indices in a BIT. Then process operations in input order: for an update (type 1 or 2) on (x, t), we find the index of t in that x's compressed list and update BIT with +1 or -1. For a query (type 3) on (x, t), we need to compute sum of all updates with time <= t. Since we have compressed times for that x that only include update times, but t might not be exactly an update time. However, we can binary search to find the largest update time <= t, and query prefix sum up to that index. Because BIT only stores updates at those specific times. Since updates only happen at those times, the sum for times between update events is constant; it equals the sum of all updates with times <= that t. So we just need to take all update times for that x, sort them, and for query we find the position of the last update time <= t using binary search on the sorted list. Then query BIT prefix sum up to that index.
Thus the offline approach works: Preprocess input to collect for each x the set of times that appear in update operations (type 1 and 2). Since queries do not affect state, we don't need to include query times in the BIT. But careful: The remove operation's validity is guaranteed; we don't need to check. So we can safely do that.
But wait: Is there any scenario where a query asks for a time that is earlier than any update time? Then the binary search would give index 0, sum=0. That's fine.
So algorithm:
- Read n.
- Store operations in an array: each op has type a, t, x.
- Create a dictionary (map) from x to a list of times that appear in updates (type 1 or 2). For each op with a in {1,2}, add t to list for that x.
- After reading all operations, for each x with non-empty list, sort the list and remove duplicates? Times are distinct overall, but for a given x there could be duplicate times? Since all times are distinct overall, there cannot be two operations with same t, so for a given x, times are distinct. So no need to deduplicate. But we might have multiple operations with same x and different times.
- Then we need to process operations sequentially. For each operation:
- If type 1: add +1 at (x, t). We need to update the BIT for x at the index of t (compressed).
- If type 2: add -1.
- If type 3: query: compute prefix sum up to largest time <= t. So find position using binary search in the sorted times list for x (if x not present, answer 0). Then query BIT up to that position, and output the result.
But there's a nuance: The remove operation is guaranteed that there is at least one instance of x at that time given the current timeline. However, if we process offline, we are not checking; we just apply -1. Since the input is guaranteed to be consistent, it's fine.
Complexities: For each x we will have a BIT of size equal to number of updates for that x (call k_x). Total updates <= n, so total BIT size O(n). Memory: O(n). For each operation, we need to locate x's structure, and within that, binary search for position (O(log k_x)) and BIT query/update (O(log k_x)). So total O(n log n).
Implementation details: We'll need to map x to an index for a structure. Since x can be up to 1e9, we can use an unordered_map or map to assign an ID to each x that appears. Then we maintain for each ID a sorted vector of times (update times) and a Fenwick tree (array of ints) of size = len(vector). When we process updates, we need to find the index of the exact time t in that vector. Since times are unique, we can use a map from (x, t) to index? But we can binary search in the sorted vector each time: update needs to find the index where t is; we know t is present because we collected all update times for that x. So we can binary search (e.g., using lower_bound). That's O(log k). That's acceptable.
But careful: For queries, we need to find the index of the largest update time <= t. Since we have the sorted times, we can use upper_bound(t) - begin to get count of times < t? Actually we need count of times <= t. So we can use upper_bound(t) - 1? Or we can use binary search to get position of last time <= t. Specifically, let idx = upper_bound(times.begin(), times.end(), t) - times.begin() - 1; if idx >=0 then sum = BIT.prefix(idx+1) (since BIT is 1-indexed). So we need to get count up to idx inclusive. Implementation: using lower_bound? Actually lower_bound returns first >= t. So if we want times <= t, we can use upper_bound(t) which returns first > t. The number of elements with time <= t is (upper_bound - begin). So if we use 0-indexed BIT, we can query prefix sum up to count = (upper_bound - begin). But careful: BIT typically is 1-indexed; we can store indices 1..size. So if we have sorted times array times[0..size-1]. For a given t, let cnt = number of times <= t = upper_bound(times.begin(), times.end(), t) - times.begin(). Then the BIT prefix sum of first cnt elements gives the sum of updates with times <= t (since updates only occur at those exact times). Because updates are placed at the indices of those times. However, note that if an update time is exactly t, then it's included because upper_bound(t) gives first > t, so times exactly t are included in the count. Indeed, if times[i] == t, then upper_bound returns index i+1, so cnt = i+1, which includes that update. But should we include an update at time t when query is at time t? As argued earlier, since times are distinct, there is no conflict: if there is an update at time t, there cannot be a query at same t. So it's okay to include it? Actually consider: if there were a query at time t and an update at time t (add) for the same x, they would be at same time. But times are distinct across all operations, so that cannot happen. So either t is a query time or an update time, not both. So if we have a query at time t, there is no update at exactly t. So including updates exactly at t is not possible because t is not an update time for that x (if it were, it would be an update operation, not query). However, there could be updates for other x at time t; but we are only considering this x. Since all times are distinct globally, no other operation shares that time, so there is no update for this x at that time. Therefore, the query time t is not present in the times list for x (unless a future update happens at same t? but times are distinct, so not). So using upper_bound(t) will give count of update times <= t, which correctly excludes any update at time t because none exist. But if we inadvertently include a hypothetical update at t, it wouldn't matter. So we can safely use cnt = upper_bound(times.begin(), times.end(), t) - times.begin(); and then query BIT prefix up to cnt. However, note: BIT indices typically start at 1; if we use 0-indexed times array, we can map index i (0-based) to BIT index i+1. So prefix sum up to cnt (where cnt is number of elements with time <= t) is simply BIT.sum(cnt). Because cnt is count of elements, so the last relevant BIT index is cnt.
But careful: When we update for a specific time t (update operation), we need to find its index. Since we know t is in times, we can use binary search to find its position pos (0-indexed), then update BIT at index pos+1 with delta.
So this works.
Edge Cases: There might be queries for x that never appear in any update. In that case, we need to output 0. In our preprocessing, we may not have an entry for that x in the map. So we should check: if x not in map (or its update list is empty), answer 0.
Thus we have an offline solution that's efficient.
Now let's test with example.
Example 1:
Ops:
1: add 5 t=1
2: query 5 t=5
3: add 5 t=2
4: query 5 t=6
5: remove 5 t=3
6: query 5 t=7
Preprocessing: updates: for x=5, times = [1,2,3] (add at 1, add at 2, remove at 3). Sorted = [1,2,3].
Process:
Step1: update at time1 => index0 -> BIT[1] +=1 => BIT sum prefix? Not used.
Step2: query t=5: cnt = upper_bound([1,2,3],5) -> all <=5 -> cnt=3 => BIT.sum(3) = current sum: we have only +1 so sum=1 -> output 1. correct.
Step3: update at time2 -> index1 -> BIT[2] +=1 => now BIT: idx1=1, idx2=1 => sum(3)=2? Actually later.
Step4: query t=6: cnt=3 => BIT.sum(3)= now +1+1=2? but we haven't applied remove yet? remove is later. So sum=2 -> output 2. correct.
Step5: remove at time3 -> index2 -> BIT[3] += -1 => now net: +1+1-1=1.
Step6: query t=7: cnt=3 => sum=1 -> output 1. correct.
Works.
Second example:
1: add 1 t=1
2: remove 1 t=2
3: query 1 t=3
Preprocessing: x=1 times [1,2] sorted [1,2].
Process:
Step1: update +1 at time1 => sum(??)
Step2: update -1 at time2 => sum...
Step3: query t=3: cnt= upper_bound(<=3)=2 => BIT.sum(2)= +1-1=0 output 0. correct.
So offline approach works.
Now need to think about memory and implementation in C++. n up to 100k, so total number of updates <= 100k. We'll have a map from x to a vector of times. Each vector may be small. For BIT per x, we need to store an array of ints of size equal to number of updates for that x. Total size O(n). Since n=100k, that's fine.
Implementation steps:
-
Read n.
-
Create arrays to store operations: type[], t[], x[] (size n).
-
Also, maintain unordered_map<int, vector> updateTimes; (or map, but unordered is faster). For each op if type !=3, push t into updateTimes[x].
But careful: if type==3 (query), we don't add to updateTimes because queries are not updates.
-
After reading, for each entry in updateTimes, sort its vector.
Optionally, we could also compress x itself: assign each distinct x an ID. For that, we iterate over updateTimes keys and assign IDs, but also queries might have x that never appear as updates. For those we answer 0. So we can assign IDs only to x values that have updates. We'll need to map x to an ID for quick access to its BIT and times vector.
So: mapXtoID: unordered_map<int, int> or map.
For each pair (x, vec) in updateTimes, assign an id (starting from 0). Store for each id: vector times (sorted), and a Fenwick tree (vector bit) of size = times.size()+1 (1-indexed). We'll allocate the BIT vector with size = sz+1 and initialize to 0.
However, we also need to handle updates that occur for x that have updates, but we must also handle queries for x that have no updates (answer 0). So we can check if x is in mapXtoID; if not, output 0 directly.
-
Process operations in order from i=0 to n-1:
For each op:
- if type == 1 or 2: delta = +1 for type1, -1 for type2.
xval = op.x, tval = op.t.
Get id = mapXtoID[xval].
Find index: pos = lower_bound(times[id].begin(), times[id].end(), tval) - times[id].begin(); // since tval exists, it's exact.
Update BIT at pos+1 with delta.
- if type == 3:
xval = op.x, tval = op.t.
Check if xval in mapXtoID.
If not: print 0.
Else:
id = mapXtoID[xval];
const vector& times_vec = times[id];
// count number of update times <= tval
int cnt = upper_bound(times_vec.begin(), times_vec.end(), tval) - times_vec.begin();
int ans = BIT_query(id, cnt); // sum over first cnt elements
print ans.
Implementation of BIT per id: Since we have many BITs, we can store a vector of vectors: vector<vector> bits; or a vector of Fenwick objects. We'll define a struct Fenwick with vector bit, and methods.
But careful: The BIT size per id = times[id].size(). So we need to allocate. The total number of BIT entries is sum over ids of (size+1) <= n + number_of_distinct_x. With n=100k, that's fine.
Now about the guarantee: "after each operation is applied all operations of the first and second types are consistent." Means that when we apply a remove, the count at that moment is >=1. This ensures that we never go negative? But our BIT will track count; it could temporarily be negative if we applied remove before add? But the guarantee says it's always valid, so with the correct order of applying updates (in input order) the count at any time t (including after the remove) will be non-negative? Actually the condition only says that when we apply a remove operation, the integer is present in the multiset (so at that moment, before removal, count >=1). After removal, count could become 0. So it's fine. But our BIT doesn't enforce anything; we just update.
Now confirm that the approach of using all update times for a given x pre-collected is valid even though updates are applied in input order. Because we are building the BIT with all possible indices, but we only update as we go. Since we know the indices in advance, it's fine. The BIT will initially be all zeros. Then each update sets a value at its index. That's correct.
Potential issue: If there are duplicate x values with same time? Times are distinct globally, so no.
Now test with more complex scenarios: Suppose we have an add at time 10, then later a query at time 5: answer should be 0 because add hasn't happened yet? But wait: The add occurs at time 10, but the query is at time 5. However, the query is performed earlier in input order? Actually consider input: first operation: add at time 10, second: query at time 5. According to the problem, we process in order: after first operation, the timeline contains an add at time 10. Then the query at time 5 asks: how many at time 5? Since the only add is at time 10 (>5), the answer is 0. That matches our method: times list for that x includes 10; for query t=5, cnt = upper_bound([10],5) = 0; BIT sum 0 = 0. Good.
Now consider: add at time 10, then later remove at time 5. But can that happen? Input order: first add at time 10, then remove at time 5. After first add, timeline: add at 10. Then we attempt to remove at time 5. Is that allowed? The guarantee says after each operation is applied, all operations of first and second types are consistent. At the moment we apply the remove (step2), we need that at time 5, there is at least one instance of x. But with only an add at time 10 (which is after 5), at time 5 the count is 0. So this would be invalid. So such sequence would not appear in input. So we don't need to worry about such case. So our offline collection of times is consistent: all update times for a given x are in arbitrary order, but when we process updates in input order, we always apply them to the BIT. Since the input is guaranteed consistent, we are fine.
Now we should implement.
Complexities: O(n log n) time, O(n) memory.
Implementation details:
- Use scanf/printf for speed.
- Use unordered_map for x to ID, but be careful: x up to 1e9, but number of distinct x <= n. unordered_map should be fine. Or use map for deterministic ordering; both O(log n) per insert during preprocessing, but that's fine.
- For storing times vectors and BIT vectors: we can have a vector<vector> times_list; and a vector BITs; but Fenwick needs a vector. We could store BIT as vector<vector> bit_arrays; but we need to update and query. Create a struct with methods. Or we can simply store for each id a vector bit, and have functions that take vector& bit and index. Since we have many BITs, we could define a class with static methods: void add(vector& bit, int idx, int delta) and int sum(vector& bit, int idx). But we need to know the size of BIT for each id; we can just pass the whole vector.
We'll implement:
struct Fenwick {
vector bit;
int n;
Fenwick(int size) : n(size), bit(size+1, 0) {}
void add(int idx, int delta) { // idx is 0-index? We'll use 1-index internal.
for (int i = idx+1; i <= n; i += i & -i) bit[i] += delta;
}
int sum(int idx) { // number of elements up to idx (0-index inclusive) i.e., prefix count idx+1
int res = 0;
for (int i = idx+1; i > 0; i -= i & -i) res += bit[i];
return res;
}
int range(int l, int r) {
return sum(r) - sum(l-1);
}
};
But for query we need sum up to cnt (which is count of times <= t). Since we want sum of updates for indices 0..cnt-1 (if cnt is count), we can call sum(cnt-1). Wait earlier we defined cnt = number of times <= t. That count corresponds to the number of update times that are <= t, i.e., the first cnt elements in the sorted times array. So to get the sum of updates for those times, we need to sum BIT values for indices 0..cnt-1 (0-index). So we need BIT.sum(cnt-1). But careful: if cnt == 0, sum(-1) is invalid; we can handle separately. So better to implement sum_prefix(int cnt) that returns sum of first cnt elements (cnt is count, not index). Let's define: int query(int cnt) { // cnt is number of elements from start, 0 <= cnt <= n. If cnt==0 return 0. else return sum(cnt-1). Or we can implement sum(int idx) where idx is 0-index inclusive; then for cnt we call sum(cnt-1). That's fine.
Alternatively, we can use BIT where indices correspond directly to positions 1..n, and we store values at those positions. Then to get sum of first cnt positions, we do bit.sum(cnt). So if we use 1-indexed BIT, we want to map update time's index pos (0-based) to BIT index pos+1. Then to get sum of updates with times <= t, we need to sum over BIT indices 1..cnt, where cnt = number of times <= t. So we can just call bit.sum(cnt). So that's simpler: in BIT class, have void update(int pos, delta) where pos is 0-index? But we can have method add(int idx, delta) where idx is 0-index, and inside we do for(i=idx+1; i<=n; i+=i&-i). And method prefix(int cnt) where cnt is number of elements (i.e., upper bound count), we can directly compute sum over first cnt indices (1..cnt) by: for(i=cnt; i>0; i-=i&-i). So we need to store BIT size n. So we can define:
class BIT {
public:
vector tree;
int n;
BIT(int n) : n(n), tree(n+1, 0) {}
void add(int pos, int delta) { // pos is 0-index
for (int i = pos+1; i <= n; i += i & -i) tree[i] += delta;
}
int sum(int cnt) { // sum of first cnt elements (cnt can be 0..n)
int res = 0;
for (int i = cnt; i > 0; i -= i & -i) res += tree[i];
return res;
}
};
For query: cnt = upper_bound(times, t) - times.begin(); then ans = bit.sum(cnt);
For update: pos = lower_bound(times, t) - times.begin(); then bit.add(pos, delta);
Thus fine.
Now we need to store for each id: times vector and BIT object. But BIT object contains a vector; we can't easily store a vector of BIT objects if BIT is not default constructible? But we can store as vector maybe; but BIT has no default constructor unless we define. We can store as vector<unique_ptr> or simply store times and bit vectors separately. For simplicity, we can store two vectors: vector<vector> times; and vector bits; but BIT is a class, we can push_back(BIT(size)) after we compute size. This requires BIT to be movable or copyable. In C++, a class with a vector member is movable automatically? Since we have custom constructor, but we can define BIT(BIT&&) = default; or rely on compiler-generated move? Actually if we don't declare any special functions, the compiler will generate move constructor and move assignment if no user-declared destructor/copy etc. Our BIT has user-defined constructor BIT(int n), but that doesn't prevent move generation. It should be fine. However, to be safe, we could store BIT as vector<vector> tree for each id and have functions that operate on that vector. But we can also store a vector of Fenwick objects using emplace_back. Let's do:
struct Fenwick {
vector bit;
int n;
Fenwick(int sz) : n(sz), bit(sz+1, 0) {}
void add(int pos, int delta) {
for (int i = pos+1; i <= n; i += i & -i) bit[i] += delta;
}
int sum(int cnt) {
int res = 0;
for (int i = cnt; i > 0; i -= i & -i) res += bit[i];
return res;
}
};
Then after sorting times for each x, we do:
ids.push_back(vector(sorted_times));
bits.emplace_back(sorted_times.size());
But careful: times for each id we need to store as a vector. We'll have vector<vector> all_times; and vector all_bits; And map x->id.
Now processing:
for i in 0..n-1:
if type[i]==1 or 2:
int id = x_to_id[x[i]];
int pos = lower_bound(all_times[id].begin(), all_times[id].end(), t[i]) - all_times[id].begin();
int delta = (type[i]==1 ? 1 : -1);
all_bits[id].add(pos, delta);
else:
if x_to_id.find(x[i]) == x_to_id.end()) print 0;
else:
int id = x_to_id[x[i]];
int cnt = upper_bound(all_times[id].begin(), all_times[id].end(), t[i]) - all_times[id].begin();
int ans = all_bits[id].sum(cnt);
print ans;
That's it.
Now about potential integer overflow: sum can be up to number of adds, up to 100k, fits in int.
Now need to be careful with reading input: The first line is n, then n lines each with a, t, x. All are ints.
Now let's test on given examples.
Example 1:
n=6
Ops as given.
Preprocess updates: x=5: times from ops 1 (add), 3 (add), 5 (remove) => times = [1,2,3] sorted.
Map: x=5 -> id=0
Processing:
i0: type1: id0, pos= lower_bound([1,2,3],1)=0, add(0,+1)
i1: type3: id0, cnt=upper_bound(...,5)=3 => sum(3): bit currently has only updated pos0 => sum(3) = bit.sum(3) should be 1? Let's compute: BIT: after add at pos0: bit.add(0,1) sets bit[1] +=1. sum(3) adds bit[3] + bit[2]? Actually in BIT, sum(cnt) sums first cnt entries. With cnt=3, it will sum tree[3] and tree[2] depending on BIT implementation. Let's simulate: BIT size=3. After add at pos0 (which corresponds to index 1 in tree), tree[1] =1; tree[2] might be updated? Standard BIT: add(pos, delta): for i=pos+1; i<=n; i+=i&-i. So pos0 -> i=1, i<=3 -> tree[1]+=1; then i+=1 => i=2, tree[2]+=1; then i+=2 => i=4 stop. So tree[1]=1, tree[2]=1, tree[3]=0. Now sum(3): i=3; res+=tree[3]=0; i-=1 => i=2; res+=tree[2]=1; i-=2 => i=0 stop. So res=1. Good.
i2: type1: id0, pos= lower_bound([...],2)=1, add(1,1). add(1): i=2 -> tree[2]+=1 (now tree[2]=2); i=4 stop. Also maybe i=... but only i=2. Then tree[1] remains 1, tree[3]=0. Now sum(3) would be: i=3 ->0; i=2 ->2; total 2. So at i3 query t=6 cnt=3 sum=2 -> correct.
i4: type2: id0, pos= lower_bound(... ,3)=2, add(2,-1): i=3 -> tree[3]+=-1 (now -1); i=4 stop. Now BIT: tree[1]=1, tree[2]=2, tree[3]=-1. sum(3): i=3 -> -1; i=2 ->2; total 1. Works.
i5: query t=7 cnt=3 sum=1 -> output 1.
So correct.
Now test with a scenario where there are multiple x's.
Edge Cases: What about an x that appears only in queries? Then we output 0. Our map won't have it, so fine.
Now complexity: building times per x: O(total updates) memory. Sorting per x: sum of O(k_x log k_x) <= O(n log n) in worst case if many distinct x each with few updates, but overall sorting each list individually sum of k_x log k_x <= n log n (since log k_x <= log n). Actually worst-case if each update is for a distinct x, then each k_x=1, sorting is trivial O(1) each, total O(n). If all updates for same x, sorting O(n log n). So total O(n log n).
Processing: each operation O(log k_x) for binary search + O(log k_x) for BIT = O(log n) per op => O(n log n). So fine.
Memory: times vectors total n entries; BIT trees total n+distinct_x entries (about n). So about 2n ints ~ 800KB for n=100k, plus overhead, fine.
Now we must note that we need to store the operations (type, t, x) to process sequentially. We can either store them in arrays or we can process in a single pass after preprocessing? But preprocessing requires knowing all updates to build times. So we must read all operations first, store them, then do preprocessing, then process them in order. That's okay.
Implementation Plan:
- Use scanf/printf.
- Define global variables: n, vector a, t, x (or a single vector of tuple).
- Read n.
- Loop i from 0 to n-1: read ai, ti, xi; store.
- Create unordered_map<int, vector> updateTimesMap.
- For i from 0 to n-1: if a[i] != 3: updateTimesMap[x[i]].push_back(t[i]).
- After reading, assign IDs.
unordered_map<int, int> x_to_id; // from value to ID.
vector<vector> times_list;
vector bits;
for (auto& entry : updateTimesMap) {
int xval = entry.first;
vector& times = entry.second;
sort(times.begin(), times.end());
x_to_id[xval] = times_list.size();
times_list.push_back(std::move(times));
bits.emplace_back(times_list.back().size()); // size = number of updates for this x.
}
- Now process operations in order:
for i from 0 to n-1:
int type = a[i], ti = t[i], xi = x[i];
if (type != 3) {
int id = x_to_id[xi];
int pos = lower_bound(times_list[id].begin(), times_list[id].end(), ti) - times_list[id].begin();
int delta = (type == 1 ? 1 : -1);
bits[id].add(pos, delta);
} else {
auto it = x_to_id.find(xi);
if (it == x_to_id.end()) {
printf("0\n");
} else {
int id = it->second;
const vector& times = times_list[id];
int cnt = upper_bound(times.begin(), times.end(), ti) - times.begin();
int ans = bits[id].sum(cnt);
printf("%d\n", ans);
}
}
This should produce correct output.
Now we need to check: The remove operation is guaranteed that integer is present. However, is there any scenario where we need to ensure that our BIT state reflects the presence? Not needed.
Now what about the fact that we used unordered_map for x_to_id. For iterating over updateTimesMap to assign IDs, we can use the same map, but note: the order of iteration over unordered_map is not important. That's fine.
Now the input size: n up to 100k, all times up to 1e9, so use int or long long? int can hold up to 1e9, fine. t and x are within 1e9, so int (32-bit signed) can hold. But sum may be up to 100k, also int.
But careful: t and x could be up to 1e9, which fits in signed 32-bit (max 2.147e9). So int is fine.
Now we need to pay attention to the fact that we store times in vector. The BIT add uses pos+1 as index; pos up to maybe 100k, fine.
Potential issue: Some compilers may require c++11 features for emplace_back with arguments. We can use bits.push_back(Fenwick(times.size())) as well.
Now let's test with some custom cases:
Case: n=1, query for x=10 at t=5, output 0. Works.
Case: n=2: add x=100 at t=10, query x=100 at t=10. Since times distinct, t_query=10, t_add=10? They must be distinct; can't have both at same t. So not allowed. Good.
Case: multiple x: add x=1 t=1; add x=2 t=2; query x=1 t=2 -> answer 1. Preprocess: x=1 times [1]; x=2 times [2]; Map: id0 for x=1, id1 for x=2. Process: add at t=1 for x=1, update BIT0. add at t=2 for x=2, update BIT1. Query: id0, cnt= upper_bound([1],2)=1, sum(1)=1. Output 1.
Works.
Now consider scenario: updates interleaved with queries, but we collected all times for each x beforehand. That includes updates that occur after a query. That's fine, as BIT is initially zero for those future updates; they will be added later when we encounter them.
Now what about removal before addition for a given x? As argued, input is guaranteed consistent, so at the moment of removal there must be a previous add (in the timeline, not necessarily input order) that ensures at that time the count is >=1. That means there is some add with time <= removal time that has been applied before the removal (in input order). But note: The removal's time could be less than some add's time that appears later in input order? That would be invalid because at the moment of removal, that future add hasn't been applied yet, but its time could be less than removal time? Actually if removal time is later than add time but add is later in input order, then at the moment of removal (in input order), the add hasn't been applied yet, so the timeline does not have that add, so the count at removal time might be insufficient. So such scenario would be invalid. Thus the guarantee ensures that when we process removal, there must already be enough adds (with times <= removal time) that have been processed (in input order). But our preprocessing includes all update times, but when we process removal, we update BIT with -1, regardless of current state. However, if the timeline had not yet added the necessary add (because add appears later in input order), then the removal would be invalid. But since the input is guaranteed valid, that case won't happen. So our method works.
Now let's think about a more subtle point: The guarantee: "after each operation is applied all operations of the first and second types are consistent." This might mean that at any moment in the timeline (after applying the current operation), for any time point, the multiset state is consistent (i.e., no negative counts). Since we apply updates in input order, this condition holds. So we don't need to worry.
Now about the performance: using unordered_map for x_to_id and for updateTimesMap is okay. But we need to sort each vector; we can sort directly.
Implementation details in C++:
#include
#include
#include
#include <unordered_map>
using namespace std;
struct Fenwick {
vector bit;
int n;
Fenwick(int n_) : n(n_), bit(n_+1, 0) {}
void add(int pos, int delta) {
for (int i = pos+1; i <= n; i += i & -i) bit[i] += delta;
}
int sum(int cnt) {
int res = 0;
for (int i = cnt; i > 0; i -= i & -i) res += bit[i];
return res;
}
};
int main() {
int n;
scanf("%d", &n);
vector a(n), t(n), x(n);
unordered_map<int, vector> updateTimes;
for (int i = 0; i < n; ++i) {
scanf("%d %d %d", &a[i], &t[i], &x[i]);
if (a[i] != 3) {
updateTimes[x[i]].push_back(t[i]);
}
}
unordered_map<int, int> xid;
vector<vector<int>> times_list;
vector<Fenwick> bits;
for (auto& p : updateTimes) {
int val = p.first;
vector<int>& times = p.second;
sort(times.begin(), times.end());
xid[val] = times_list.size();
times_list.push_back(times);
bits.emplace_back(times.size());
}
for (int i = 0; i < n; ++i) {
int type = a[i], ti = t[i], xi = x[i];
if (type != 3) {
int id = xid[xi];
int pos = lower_bound(times_list[id].begin(), times_list[id].end(), ti) - times_list[id].begin();
int delta = (type == 1) ? 1 : -1;
bits[id].add(pos, delta);
} else {
auto it = xid.find(xi);
if (it == xid.end()) {
printf("0\n");
} else {
int id = it->second;
const vector<int>& times = times_list[id];
int cnt = upper_bound(times.begin(), times.end(), ti) - times.begin();
int ans = bits[id].sum(cnt);
printf("%d\n", ans);
}
}
}
return 0;
}
Check: bits.emplace_back(times.size()) constructs a Fenwick with size times.size(). However, when we later push back times_list, we need to ensure that the times vector is not invalidated. We push times (which is the sorted vector from the map). After we move it into times_list, p.second might be in an unspecified state. But that's fine because we no longer need the map after this. However, we used p.second for sorting and then moved it. Actually we sorted p.second, then we do times_list.push_back(times) which copies? We have vector& times = p.second; then we push_back(times) - that copies the vector. That's okay but uses extra memory. We could move it: times_list.push_back(std::move(times)); to avoid copy. After moving, p.second is empty, but we don't need it later. So better to use std::move to reduce memory. However, after moving, we still need the size for bits.emplace_back. So we need size before move? Actually we can compute size = times.size(); then times_list.push_back(std::move(times)); bits.emplace_back(size); That's fine.
But if we copy, it's okay; total memory would be double for times (once in map, once in times_list). Since total updates <=100k, it's not huge. But better to avoid duplication.
We can do:
for (auto& p : updateTimes) {
sort(p.second.begin(), p.second.end());
xid[p.first] = times_list.size();
times_list.push_back(std::move(p.second));
bits.emplace_back(times_list.back().size());
}
After moving, p.second is empty, but we don't need it.
Now, check that bits.emplace_back uses times_list.back().size() which is correct.
Now, about the BIT sum method: For cnt=0, bits[id].sum(0) returns 0 because the for loop does i=cnt; i>0; ... so if cnt=0, loop is skipped, returns 0. Good.
Now, check for updates: When we call add(pos, delta), we use pos which is index from 0 to size-1. In BIT.add, we do for i=pos+1; i<=n; i+=i&-i. That works.
Now, potential bug: For query, we compute cnt = upper_bound(times, ti) - times.begin(). But suppose there is an update with time exactly ti? As argued, times are distinct and if ti is query time, it cannot be an update time for same x. So cnt includes updates with time <= ti. Since no update with time = ti, it's fine. But what if there is an update for a different x with time = ti? That doesn't affect. So correct.
Now test on a case where there are multiple updates for same x but with times not sorted relative to input order. For example:
n=3:
1 5 10 (add x=10 at t=5)
2 3 10 (remove x=10 at t=3)
3 6 10 (query x=10 at t=6)
Is this valid? At step2, we attempt to remove at t=3. The timeline currently: we have added at t=5. At t=3, there is no add (since add at t=5 >3). So count=0, removal invalid. So input not allowed. So such case won't appear.
Now test valid case:
1 1 10 (add at t=1)
2 3 10 (remove at t=3) -> valid because at t=3, count from add at t=1 is 1.
3 2 10 (query at t=2) -> answer should be 1 (since add at t=1, no remove yet at t=2). Input order: after step1, timeline: add at 1. step2: remove at 3. step3: query at 2. At that point, timeline has add at 1 and remove at 3. Count at t=2 is 1. So answer=1. Our method: updates times for x=10: [1,3]; sorted [1,3]. Process:
i0: add at pos0 => BIT sum for cnt? Not yet.
i1: remove at pos1 => BIT add -1.
i2: query t=2: cnt = upper_bound([1,3],2) = index of first >2 -> element 3 is >2, so cnt=1 (only time 1). BIT sum(1) = sum over first 1 element: we have +1 at index0, -1 at index1? Wait, BIT sum(1) only includes the first element (index0). The remove at index1 is not included because it's at time 3 >2. So sum=1. That's correct. So good.
Now test case where query time is less than earliest update: answer 0.
Now consider scenario where after some updates, we query for a time that is between update times. Our method uses upper_bound to get count of update times <= t, then BIT sum over those positions. Since BIT stores updates only at those exact times, the sum of updates with time <= t is exactly what we need. Good.
Now check for potential off-by-one in BIT sum when cnt equals the number of updates. That's fine.
Now memory and time constraints: n=100k, sorting total O(n log n) around 1.6 million operations, fine. Binary searches per operation: up to 2 per op (one for lower_bound/upper_bound and BIT O(log n)). Overall fine.
Now one more nuance: The input guarantees that all moments of time are distinct. But does that apply across all operations (including queries)? Yes, "all moments of time are distinct". So t values are unique across all operations. So indeed no two operations share same t. This is important for our reasoning about query times not coinciding with update times for same x.
Now, can we have an update and a query with same t but different x? Since times are distinct globally, no. So any given t appears exactly once across all operations. So if it's an update for x=5, it cannot be any other operation (including query for any x). So our assumption holds.
Now, is there any case where an update (add/remove) occurs at a time that is after a query time, but the query asks for a later time? That's fine.
Now, ensure that we handle the case where x appears in updates but later a query uses a time that is less than the smallest update time. Then cnt=0, sum=0, output 0.
Now, we must consider that we used unordered_map for x_to_id. In C++, unordered_map on int is fine, but we need to include <unordered_map>. Also, we used vector bits; Fenwick should be movable. Usually, with user-defined constructor, the move constructor is not automatically generated? Actually in C++11, if we don't declare any copy/move constructors or destructor, the compiler will generate a move constructor that moves each member (vector bit is movable). However, the presence of a user-defined constructor does not suppress the generation of move operations. Only declaring a copy constructor, copy assignment, destructor etc. might suppress. Since we have no declarations, the move constructor should be implicitly generated. But to be safe, we can store bits as vector<unique_ptr> or vector<Fenwick*> and allocate new Fenwick. But I think it's okay.
Alternatively, we can avoid storing Fenwick objects and store a vector of vectors for BITs and have standalone functions. But storing Fenwick is simpler.
Testing with some compilers: Usually it's fine.
Now, check for reading and writing: Use scanf/printf.
Now, let's think about alternative approach using order statistic tree online, but offline is simpler.
Now, confirm that the offline approach respects the "after each change he makes all delete operations are applied only to element that is present in the multiset." This condition ensures that the BIT never goes negative for a particular prefix? Actually not necessary.
Now, consider potential integer overflow in BIT sum: we use int; max sum of absolute values maybe up to number of adds, which is at most 100k, safe.
Now, we are done.
But wait: There's a catch. In the preprocessing, we collected times for updates only. However, what about queries? They are not needed. But there is a nuance: The remove operation at time t is guaranteed that the element is present at that moment. In terms of cumulative sum, it means that the prefix sum up to time t (including the remove itself? Actually the remove itself happens at time t, and before applying it, the count must be >=1. After applying it, the count becomes (prefix sum up to times < t) + (maybe adds at time t? But there is no other operation at same t). Since the remove itself is a -1 at time t, the condition is that the sum of deltas for times < t is >= 1. The remove will then reduce that to >=0. So it's okay.
Now, is there any scenario where the removal occurs at a time where the sum of deltas for times <= t (including other removes?) might be negative? Not if condition holds.
Now, our approach does not need to enforce, so fine.
Now, test more complex scenario: multiple adds and removes interleaved with queries, and multiple x.
We'll implement and test with random small cases by brute force.
But before coding, think about constraints: ti, xi up to 1e9, n up to 100k. Our data structures use int, fine.
Now, double-check that we treat times as ints; we should use long long? Not necessary.
Now, there is a potential pitfall: In some problems, they require using long long for sum because many adds, but here count can't exceed n, so int is fine.
Now, we should verify that the method works when there are multiple updates for same x at same time? Times are distinct globally, so impossible.
Now, think about memory usage of map: We used unordered_map<int, vector>. After we moved vectors into times_list, we still have the map with empty vectors? Actually we moved from p.second, but p.second becomes empty after move? Not necessarily guaranteed; but it's fine if we don't use it later. After the loop, we could clear the map to free memory, but not needed.
Now, let's ensure we treat the case where updateTimes[x] may have been sorted and then moved, but we still need to access times_list for that x later. We have xid mapping to index.
Now, about the order of processing: we have to process operations in order. Our for loop does that.
Now, is there any case where we need to consider that the BIT sum returns the cumulative count at time t? Yes.
Now, I think it's correct.
Let's also test with a scenario where a query appears before any updates for that x. Should output 0. Works.
Now, test with a scenario where we have both add and remove for same x, but query at a time between them.
All good.
Now, we can implement.
But before finalizing, consider the possibility of using a Fenwick tree over compressed times per x, but we could also compress times globally across all x? Not directly because each x has its own BIT. But we could use a 2D BIT: compress times globally and maintain a map from x to something? But it's easier this way.
Now, we should also handle the case where the same x appears in both add and remove, and we need to answer queries. Our method handles.
Now, I'll write the code.
Potential micro-optimizations: Use reserve for unordered_map? Not needed.
One issue: For each query, we call upper_bound on the times vector. That's O(log k). Good.
For each update, we call lower_bound to find the exact index. Also O(log k).
Now, about the use of lower_bound vs binary search: Since we know the time exists, we could store a mapping from (x, t) to index during preprocessing. Because we have all update times, we could precompute for each update operation the index. That would avoid binary search during processing. But we need to know the index for each update operation individually. Since we have all operations stored, we could, during preprocessing, for each x, after sorting times, build a map from time to index. Then during processing, we can quickly get index. However, that would require extra memory (a map per x) or a global unordered_map with key combined (x,t). Given n=100k, we could store for each operation its index during preprocessing: While building times, we could also store for each update operation a precomputed position. But we don't know which operations are updates until we read all? Actually we can in first pass read all operations, store them, and also fill updateTimes. Then in a second pass, after sorting times for each x, we could for each update operation compute its index by binary search or by building a dictionary. Since we will later process operations sequentially, we could for each update op compute its index and store it, to avoid binary search at runtime. That might reduce constant factor. But not necessary; O(log n) per operation is fine.
But we need to be careful: In the processing loop, we are already doing binary search for each update. That's fine.
However, note that we already have the times list sorted, and for each update we need to find its position. We can use binary search each time. With 100k operations, 2100k * log(100k) ~ 2100k*17 = 3.4M operations, trivial.
Now, ensure we use fast I/O: scanf/printf.
Now, code.
But before final code, think about potential issues with moving vectors: In the loop:
for (auto& p : updateTimes) {
sort(p.second.begin(), p.second.end());
xid[p.first] = times_list.size();
times_list.push_back(std::move(p.second));
bits.emplace_back(times_list.back().size());
}
But after moving p.second, its state is unspecified; but we don't use it later. So it's fine.
Now, note that we used unordered_map for updateTimes; but when we iterate over it, the order is arbitrary. That's fine.
Now, need to include ? Actually we use cstdio. Also include , , <unordered_map>.
Now, compile.
Now, test with given examples.
We'll run mental test.
Example 1: Already done.
Example 2:
3
1 1 1
2 2 1
3 3 1
Preprocess: updates: x=1 times [1,2] sorted.
Processing:
i0: add pos0 => BIT add +1.
i1: remove pos1 => BIT add -1.
i2: query x=1, t=3: cnt = upper_bound([1,2],3)=2, BIT sum(2) = +1-1=0 output 0.
Correct.
Now test edge case: n=1, query: 3 5 10 -> output 0. Preprocess: no updates for x=10. xid does not contain 10. During processing, it's a query, it->second not found, output 0. Good.
Now test with multiple x:
4
1 1 5
1 2 10
3 3 5
3 4 10
Preprocess: x=5 times [1]; x=10 times [2].
Process:
i0: add 5 pos0 => BIT5 add +1.
i1: add 10 pos0 => BIT10 add +1.
i2: query 5 t=3: cnt = upper_bound([1],3)=1, BIT5 sum(1)=1 output 1.
i3: query 10 t=4: cnt = upper_bound([2],4)=1, BIT10 sum(1)=1 output 1.
Works.
Now test with interleaved where removal happens before add but times ensure consistency: Suppose input:
1 1 5 (add at t=1)
2 3 5 (remove at t=3) // valid because add at t=1
3 2 5 (query at t=2) // expect 1
Process: times for x=5: [1,3]. Sorted [1,3].
i0: add pos0 => +1
i1: remove pos1 => -1
i2: query t=2: cnt = upper_bound([1,3],2)=1 => sum(1)=1 output 1.
Works.
Now test where removal occurs at a time earlier than some add but still valid because add with earlier time exists: Already.
Now test scenario with multiple adds and removes and queries interleaved.
I think it's correct.
Now, I will produce final answer code.
But before final, ensure that the BIT sum method is correct: In BIT, we store values at positions 1..n corresponding to times sorted. When we call bits[id].sum(cnt), we need to pass cnt as the number of positions to sum (i.e., the count of times <= t). Our BIT.sum implementation sums first cnt elements, i.e., indices 1..cnt. This is correct because we inserted updates at the positions corresponding to sorted times.
Now, careful: The BIT add method uses pos (0-index) and updates tree at index pos+1. So after we insert at position p, that corresponds to the (p+1)th element. Then sum(cnt) sums first cnt elements, which are positions 0..cnt-1. So for cnt=1, it sums only the first element, which corresponds to the smallest time. So when we compute cnt = number of times <= t, that includes all updates with times <= t. So indeed we sum those positions.
Thus it's correct.
Now, final code.
Potential issue: Use of unordered_map may be slower due to hashing of int, but fine.
Now, could we have a scenario where an x appears only in queries and also in updates? That's fine.
Now, note: The input guarantees that after each operation, all operations of types 1 and 2 are consistent. This may have implications for removals that depend on future adds? Not allowed. So fine.
Now, provide final solution.
Time complexity: O(n log n).
Now, I'll produce the final answer in the required format (just code? The answer should be the output for each query). We'll output each answer on a new line.
Now, final code.
But before writing final, check if we need to use long long for t and x? They are within 1e9, int is fine.
Now, let's produce the final solution.
Potential improvements: Use vector<pair<int,int>> to store operations; but arrays are fine.
Now, write.
One more test: random small test with brute force simulation: Simulate timeline as map from time to delta? But we trust.
Now, finalize.
Edge Cases: If there is an x with many updates, sorting and binary search works.
Now, think about memory: For each x, we have times vector and BIT vector. BIT vector of size k+1. The total of k across all x is total updates. So memory ~2100k4 bytes = 0.8 MB, plus overhead for vectors (pointers, capacity) maybe a bit more but still < 64 MB.
Now, compile and run.
I think it's correct.
But there is a potential nuance: The problem statement says: "Artem wants to create a basic multiset of integers. He wants these structure to support operations of three types..." Then about time machine: "Artem doesn't simply apply operations to the multiset one by one, he now travels to different moments of time and apply his operation there." The example shows that queries are answered based on the timeline as it exists at that moment, considering all previous operations (in his travel sequence) that have been applied, regardless of their time order. That's exactly our interpretation.
Thus our solution is correct.
Now, I'll produce final code.
One more thought: Could there be a scenario where an update (add or remove) occurs at a time that is before some previously applied operation's time? Yes, that's the essence of time travel. In that case, the timeline changes; and subsequent queries need to consider that new event. Our BIT updates accordingly. Since we have pre-collected all update times, we can update at its index.
Now, confirm that the BIT sum for a query after an update that occurred at an earlier time than some previous updates will correctly account for that new event because it updates the BIT at the appropriate index, and future queries will include it.
Now, one more nuance: When we update at a time t, we add delta to BIT at its index. But if there are later updates (in input order) that also affect the same x, they will also be added. So the BIT's prefix sum at any point reflects exactly the events added so far.
Now, we must be careful that we are not allowed to pre-initialize BIT with all updates because they might not have been applied yet. But we only add them as we go. Since BIT initially zero, it's fine.
Now, output: each answer on new line.
Now, final code.
Let's write in C++.
After writing code, I'll test with the given examples.
I'll implement as described.
Potential improvements: Use map for updateTimes and xid? But unordered_map is fine.
I'll add:
ios::sync_with_stdio(false); cin.tie(0); for faster I/O? But we use scanf/printf, so not needed.
Now, code:
#include <cstdio>
#include <vector>
#include <algorithm>
#include <unordered_map>
using namespace std;
struct Fenwick {
vector<int> bit;
int n;
Fenwick(int n_) : n(n_), bit(n_ + 1, 0) {}
void add(int pos, int delta) {
for (int i = pos + 1; i <= n; i += i & -i) {
bit[i] += delta;
}
}
int sum(int cnt) { // sum of first cnt elements (0 if cnt==0)
int res = 0;
for (int i = cnt; i > 0; i -= i & -i) {
res += bit[i];
}
return res;
}
};
int main() {
int n;
scanf("%d", &n);
vector<int> a(n), t(n), x(n);
unordered_map<int, vector<int>> updateTimes;
for (int i = 0; i < n; ++i) {
scanf("%d %d %d", &a[i], &t[i], &x[i]);
if (a[i] != 3) {
updateTimes[x[i]].push_back(t[i]);
}
}
unordered_map<int, int> xid;
vector<vector<int>> times_list;
vector<Fenwick> bits;
for (auto& p : updateTimes) {
sort(p.second.begin(), p.second.end());
xid[p.first] = (int)times_list.size();
times_list.push_back(move(p.second));
bits.emplace_back((int)times_list.back().size());
}
for (int i = 0; i < n; ++i) {
int type = a[i];
int ti = t[i];
int xi = x[i];
if (type != 3) {
int id = xid[xi];
const vector<int>& times = times_list[id];
int pos = lower_bound(times.begin(), times.end(), ti) - times.begin();
int delta = (type == 1) ? 1 : -1;
bits[id].add(pos, delta);
} else {
auto it = xid.find(xi);
if (it == xid.end()) {
printf("0\n");
} else {
int id = it->second;
const vector<int>& times = times_list[id];
int cnt = upper_bound(times.begin(), times.end(), ti) - times.begin();
int ans = bits[id].sum(cnt);
printf("%d\n", ans);
}
}
}
return 0;
}
Now, test with examples.
Example1:
Input:
6
1 1 5
3 5 5
1 2 5
3 6 5
2 3 5
3 7 5
Our program should output:
1
2
1
Matches.
Example2:
3
1 1 1
2 2 1
3 3 1
Output: 0
Matches.
Now, consider large input to test performance. Should be fine.
Now, check for possible bug: In the processing loop, for update operation we compute pos using lower_bound on times vector. But we should ensure that times vector is not empty; it's not because the x appears in updateTimes, so at least one update. So fine.
Now, about the move: after moving p.second, we still use p.second.size()? Not after move. We push back moved vector, then get its size. That's okay.
Now, consider if there is an x with no updates (only queries). It won't be in updateTimes, so xid doesn't have it; queries will output 0.
Now, final code.
We could also use map for xid, but unordered_map is okay.
Now, note: In the processing loop, we call lower_bound on times for each update; but we could store for each update its position during preprocessing to avoid binary search. Not necessary.
Now, final answer.
But I want to check one more scenario: Suppose there is an x with updates, and a query at time t that is less than the smallest update time. Then cnt = 0, sum(0) = 0, output 0. Good.
Now, everything seems fine.
Now, produce final answer with explanation and code.
Given the problem statement, we need to "Help Artem implement time travellers multiset." Output each answer.
Thus final solution: offline preprocessing per value with BIT.
Now, I'll output final answer as code.
But maybe we need to consider using long long for BIT sum if count could be large? But n=100k, int is fine.
Now, final answer. ```cpp
#include
#include
#include
#include <unordered_map>
using namespace std;
// Fenwick tree (Binary Indexed Tree) for one value
struct Fenwick {
vector bit;
int n;
Fenwick(int n_) : n(n_), bit(n_ + 1, 0) {}
// add delta at position pos (0‑based)
void add(int pos, int delta) {
for (int i = pos + 1; i <= n; i += i & -i)
bit[i] += delta;
}
// sum of the first cnt elements (cnt can be 0)
int sum(int cnt) {
int res = 0;
for (int i = cnt; i > 0; i -= i & -i)
res += bit[i];
return res;
}
};
int main() {
int n;
scanf("%d", &n);
vector<int> a(n), t(n), x(n);
unordered_map<int, vector<int>> updateTimes; // for each value, collect its update moments
for (int i = 0; i < n; ++i) {
scanf("%d %d %d", &a[i], &t[i], &x[i]);
if (a[i] != 3) // only add/remove are updates
updateTimes[x[i]].push_back(t[i]);
}
// assign an id to every value that appears in updates,
// sort its moments and create a Fenwick tree
unordered_map<int, int> valueToId;
vector<vector<int>> timesList;
vector<Fenwick> bits;
for (auto& p : updateTimes) {
sort(p.second.begin(), p.second.end());
valueToId[p.first] = (int)timesList.size();
timesList.push_back(std::move(p.second)); // move the sorted list
bits.emplace_back((int)timesList.back().size()); // create BIT of that size
}
// process operations in the given order
for (int i = 0; i < n; ++i) {
int type = a[i], ti = t[i], xi = x[i];
if (type != 3) { // add or remove
int id = valueToId[xi];
const vector<int>& times = timesList[id];
int pos = lower_bound(times.begin(), times.end(), ti) - times.begin();
int delta = (type == 1) ? 1 : -1;
bits[id].add(pos, delta);
} else { // query
auto it = valueToId.find(xi);
if (it == valueToId.end()) {
printf("0\n");
continue;
}
int id = it->second;
const vector<int>& times = timesList[id];
int cnt = upper_bound(times.begin(), times.end(), ti) - times.begin();
int ans = bits[id].sum(cnt);
printf("%d\n", ans);
}
}
return 0;
}