We need to process a sequence of k operations (up to 40k) on a graph of n vertices (up to 40k), with dynamic edge insertions and deletions, and connectivity queries (u, v). We need to answer each query (type 3) with YES or NO.
We have constraints: n up to 40k, k up to 40k. So total operations are moderate. However, we need to support dynamic connectivity with deletions and insertions. Standard dynamic connectivity can be solved with offline approach using divide and conquer on time (segment tree) with DSU rollback. This is typical problem: offline dynamic connectivity. Given that operations are only edge insertions and deletions and connectivity queries, we can use offline algorithm: process each edge's lifespan across the timeline, and insert it into a segment tree covering intervals of time when it is present. Then we traverse the segment tree recursively, using a DSU with rollback (persistent union-find) to maintain connectivity for that segment, and answer queries at leaf nodes (time points). Since we have up to 40k operations, offline method is feasible.
But careful: The input includes operations in chronological order. Edge insertions (type 1) guarantee that edge is not present. Edge deletions (type 2) guarantee that edge is present. So each edge (u,v) (with u<v) appears as insertion followed by deletion (or may be inserted and never deleted, but we can treat it as present until the end of timeline). Since operations are guaranteed to be consistent, we can compute each edge's active interval.
But we also need to handle queries (type 3). They ask at the moment after processing that operation? Typically, in dynamic connectivity offline processing, we treat each operation as a point in time. The sequence of k operations defines times t = 1..k. For queries at time t (operation index), we need to answer based on the set of edges active at that time, which includes edges that have been inserted and not yet deleted. Since operations happen one by one, the state after processing the operation at time t is considered. Usually, we treat each operation as instantaneous, and we need the state after applying that operation? But connectivity queries: they ask "Determine if the rabbits in the hut u and v can be played." Usually, the query occurs after all previous operations (including earlier ones) have been applied. So at the moment of query, the graph state is defined by all insertions and deletions up to that point. So for offline processing, we need to consider the timeline of events: The edges have intervals of being active. For each query at time t, we need to check connectivity in the graph formed by edges that are active at that exact time.
Thus we can treat each operation index as a time point. Edge insert operation at time t: the edge becomes active from time t+1? Or at time t after the insertion? Let's be precise: The sequence: we have operations in order. Each operation changes the state immediately. When we get a query at time t (the t-th operation is a query), we need to answer based on the state after processing previous operations (including possibly the insertion of edge earlier at time t' < t). But does the query see the effect of any earlier operations of same time? Since they are sequential, after processing the operation at index i, we answer query if it's type 3. So the state at query time i includes the insertion of edges that occurred at earlier indices, and also any deletion at earlier indices. Also, it includes the insertion if the operation itself is an insertion? Actually, the query is at a specific index i; at that moment, the operation is of type 3, so it doesn't change the state. So the state is after all operations up to i-1. But careful: Could there be a query after an insertion at same index? No, each index is either an insertion, deletion, or query. So for query at index i, the state is after applying all operations for j < i. So we need to treat the state at the moment before the query, i.e., after processing all previous operations. So we can model edge active intervals as: when an insertion occurs at time t_ins, the edge becomes active from that moment onward (starting at time t_ins+1? Actually we can consider that after the insertion operation is executed, the edge is present for subsequent operations. So if we treat time as discrete steps between operations, we can consider that the state for the query at time i (the i-th operation) is the set of edges that have been inserted at times < i and not yet deleted at times < i (i.e., before the query). So the active interval for an edge should be from the insertion time index (the moment after that operation) until just before its deletion time index (if any). So one common approach: assign each edge an interval [l, r) where l is the time index of insertion operation (i.e., the operation number, say from 1 to k) + 0.5? Alternatively, treat time points as between operations. However, the segment tree approach usually treats time as integer points (the operation indices) where queries occur, and edges are active over ranges of these integer times. To map correctly, we can define for each operation i, the state used to answer query at i is the set of edges that are active at time i. We need to decide which edges are considered active at integer time i. One typical way: When we process offline, we treat each edge's lifespan as: if inserted at time ins and deleted at time del (del > ins), then the edge is active for all times t such that ins < t ≤ del? Or ins ≤ t < del? Usually, we treat the operation index as the moment after that operation. For insertion at index i, the edge becomes active starting at time i (after i). For deletion at index i, the edge is removed before time i (so not active at i). Alternatively, we can treat the state after processing operation i as the state for queries that happen at i if it's a query. So if we assign a time to each operation index, we can think of the state as the set of edges after applying operation i, but only for query operations we output. So for an insertion at i, after that operation, the edge is present. So if a query occurs at i+1, it should see the edge. Therefore, the edge is present for all times > i until it's deleted. For a deletion at j, after that operation, the edge is removed. So for a query at j, since the query is the operation itself, it should see the state before the deletion? Actually, the operation order: At index j, we have a deletion operation. The deletion operation is executed: it removes the edge. After that, the state is updated. But the query is not at that index; it's the deletion itself, so we don't answer a query. So if a query occurs at index j, it's a separate operation, not a deletion. So for query at index j, we apply all operations with indices < j. So if a deletion occurs at index d < j, then edge is not present. If a deletion occurs at index d = j, it's not possible because j is a query. So the edge is present for queries with index > insertion index and ≤ deletion index-1? Actually, if deletion occurs at index d, then after processing operation d, edge is removed. So for any query with index > d, edge is not present. For query with index = d, we would have processed all operations < d, which includes the insertion but not the deletion, so edge would still be present if we considered state before operation d? But operation d is a deletion, not a query. So we never have a query at the same index as a deletion. So we can safely define that for a query at time i, the state is after processing all operations with index < i. So we need to know for each edge the times when it is present for queries. If edge inserted at index ins, then for any query at index i such that ins < i and (if deletion occurs at del) i ≤ del? Actually, after insertion at ins, the edge is present for all subsequent operations until before deletion. So if deletion occurs at del, then for query at i, if i < del? Because before processing operation del, the edge is still present. But if i = del, we are at deletion operation, not query. So we can say for queries at indices i where ins < i and i < del (if del exists) or i > ins if no deletion (i.e., until end). So we can treat active interval for the edge as (ins, del) if deletion exists, else (ins, k+1). But queries occur at integer indices, and we can treat the segment tree with range [ins+1, del] (inclusive) if deletion exists, else [ins+1, k]. Actually, we need to include queries at indices that are between insertion and deletion. If del is the index of deletion operation, then after processing del, edge is gone. So for query at index del, it doesn't exist. So the last query that should see the edge is del-1. So the active range is [ins+1, del-1] inclusive. For insertions without deletion, active range is [ins+1, k] inclusive (since queries up to the last operation). Also note: Insert and delete operations themselves are not queries, so we don't need to answer at those indices. So we can safely map active intervals as: for an edge inserted at time l (operation index) and deleted at time r (if exists), then it is active for query times in (l, r) i.e., l+1 ... r-1. And we can ignore time points that are not queries. In the segment tree method, we will insert the edge into the segment tree covering those intervals (as segments). Then we traverse and answer queries at leaf nodes that correspond to query operation indices.
But we have to be careful: There could be multiple insert/delete of the same edge? The problem statement: "A passage connecting huts u and v is constructed. Appears only when there is no passage connecting huts u and v." And "The passage connecting huts u and v is destroyed. Appears only when there is a passage connecting huts u and v." So each edge can be inserted and deleted multiple times? It says the construction and destruction are carried out one by one. The conditions guarantee that at the time of insertion, there is no such edge; at the time of deletion, it exists. So it could be that after deleting, it may be inserted again later. So an edge can appear multiple times across the timeline. So we need to treat each insertion-deletion pair as a separate interval. So we can maintain a map that tracks for each edge, the last insertion time if it's currently present. When we see an insertion, we record that as the start time. When we see a deletion, we close that interval with the deletion time. At the end, any edges still inserted (not deleted) have open intervals until the end.
Thus we can preprocess all operations to extract intervals for each edge (u,v). Also, we need to collect all queries: each operation type 3 at index i with (u,v). We'll assign an answer array for each query.
Then we build a segment tree over the time range 1..k (or maybe 0..k). Typically we use a segment tree over the array of operation indices that are queries. But it's simpler: we will assign each operation index i to a leaf in the segment tree. But we only need to process leaves that correspond to query operations. However, the segment tree approach usually uses the time axis as integer indices from 1 to k, and at each leaf i, if it's a query, we answer; otherwise, skip. And the DSU is built as we traverse.
But note: Insertions and deletions themselves are also at some indices, but we don't need to answer there. However, the segment tree intervals for edges cover ranges of indices where the edge is active. That includes times that might be insertion or deletion indices? But edges should be active only for queries between, not for the insertion/deletion times themselves. However, we are only going to query at leaves that are queries. In the recursion, when we add edges to the segment tree, we add them to nodes that cover the whole active interval. At the leaf representing an insertion or deletion time, we will have those edges added (if the interval includes that leaf). But if we add edges that are not actually active at that exact time (since at insertion time, after insertion, edge is present; but we consider active interval starting after insertion, not including insertion time). However, in our mapping we set active interval as [ins+1, del-1]. That excludes the insertion and deletion times. So edges will not be added to leaves representing those times. So it's fine.
Alternatively, some implementations treat the active interval as [ins, del) meaning edge active from ins (after operation) until del (before operation). This would include the insertion time? If we treat leaf times as after each operation, we can re-index. But it's simpler to use the (ins+1, del-1) mapping.
One nuance: Suppose an insertion occurs at index i and then a query at the very next index i+1. That query should see the edge. Our mapping: active interval includes i+1, yes. So good.
Now we need to implement offline dynamic connectivity using segment tree + DSU with rollback.
Given constraints: n up to 40k, k up to 40k. So total number of edges intervals: at most number of insert operations (which is at most k). So up to 40k intervals. Segment tree will have O(k) nodes, about 4*k. For each interval, we add the edge to O(log k) nodes. Then during traversal, we maintain a DSU with rollback. The DSU supports union by rank/size and undo operations. Each union operation can be rolled back if we store a stack of changes. The number of union operations across all nodes is O((number of intervals) * log k) which is O(k log k) ≈ 40k * 16 ≈ 640k. That's fine.
We'll implement DSU with parent, size (or rank), and a stack to record changes (node, previous parent, previous size). We'll need to support find with path compression? Usually, for rollback DSU, we avoid path compression because it complicates rollback; we use union by size/rank only, giving O(log n) amortized per operation, and we can rollback in O(1) per change. With up to 640k union operations and also queries (up to 40k), log n is fine.
Now design:
-
Read n, k.
-
For i from 1 to k (1-indexed):
read type, u, v.
store op[i] = {type, u, v}
-
We'll process to build intervals.
Use a dictionary (map) that maps edge (u,v) -> last_insertion_time (or maybe a stack? Since edges can be inserted and deleted multiple times, but they guarantee that before insertion it's absent and before deletion it exists, so we can just track the last insertion time. When we see an insertion of edge e, we set start[e] = i. When we see a deletion of e, we have an interval [start[e]+1, i-1]. Then clear start[e]. Also, there could be multiple overlapping intervals? They cannot overlap because edge can't be inserted while already present. So it's fine.
-
After processing all operations, for any edge e with start[e] not None, we add interval [start[e]+1, k] (since active until the end, after insertion to the last query maybe after last operation? Actually, queries can be up to k. So after last operation, there may be no further operations. But if there is a query at index k, it's included. So interval is [start+1, k] inclusive.
-
Also, there could be queries that occur at index i. We'll record query indices and the pair (u,v). For each query, we'll store its order in output.
-
Build a segment tree over the time indices 1..k. Each node has a vector of edges (pairs) that are active throughout the whole interval of that node. The segment tree is built by inserting each interval (l, r) into nodes that cover it. Standard segment tree addition: function add_interval(node, node_left, node_right, query_left, query_right, edge). If query_left <= node_left and node_right <= query_right, then push edge to node's list; else recursively to children.
-
Then we do a DFS traversal of segment tree, where at each node we apply all edges in its list to DSU (union operations), then if node is leaf (node_left == node_right) we check if op[node_left] is a query (type 3) and if so answer accordingly (check find(u) == find(v)). After that, we rollback the unions done at this node before returning to parent.
-
DSU with rollback: We'll maintain arrays parent (size n) initially parent[i]=i, size[i]=1. We'll maintain a history stack: each change records (node, prev_parent, prev_size) maybe only for the node whose parent changes (the root that gets attached). Actually, when doing union by size: find root of u and v (without compression). If roots are same, do nothing and push a marker? Usually we push a boolean indicating whether union happened, and if so, we record the changes to parent and size. We'll have a stack of actions to undo. When union is performed, we attach smaller tree under larger tree, and we change parent of the smaller root and update size of larger root. So we push onto stack a tuple representing these changes: (changed_root, previous_parent, changed_root_size? Actually we need to revert parent of the smaller root to itself, and restore the size of the larger root. Typically we push a pair of changes: (small_root, old_parent) and (big_root, old_size). But we can push a combined record: (small_root, old_parent, big_root, old_size). Or simpler: push two entries: (small_root, old_parent) and (big_root, old_size). Then when undoing, we pop and revert in reverse order.
But we must ensure that the number of pushes is constant per union (e.g., 2). And we can also push a marker to know how many to pop after leaving a node.
In the DFS, before processing children, we record the current stack size. Then after returning from children, we rollback to that size.
Implementation details:
- DSU class:
- parent: vector
- sz: vector (size of set)
- stack: vector<pair<int, int>>? Actually we need to store both parent changes and size changes. Could store as a struct with type but we can simply store the changes as a tuple (v, previous_value, is_parent?) But easier: store two separate stacks? Another common method: use a single stack where each entry is (node, previous parent, previous size). But when we change parent of small root, we also change size of big root. So we could push two entries: (small_root, parent[small_root]), and (big_root, sz[big_root]). Then on undo, pop the last entry and restore that value. But we need to know which field to restore. If we store both parent and size in separate arrays, we can push (index, old_parent) for parent changes, and (index, old_size) for size changes, but they are different types. We can have a single stack that stores (index, old_parent, old_size, flag) but that's heavy.
Simpler: push a pair (index, old_parent) when we modify parent, and also push (index, old_size) when we modify size. But we need to know which array to restore: parent or size. We could push a struct with an identifier for the array. Or we could use a single array 'ds' where we store both? Another approach: represent each change as (node, previous value) and store a separate flag indicating which attribute? Actually, we can store the previous value of parent[ node ] and then after union we update both; we can push two entries onto a stack that contain enough information to revert: e.g., we can store a tuple (type, node, old_value) where type 0 for parent change, 1 for size change. Then on undo, we check type and restore accordingly.
But we can also implement rollback DSU more elegantly: we maintain a stack of "changes" where each change is a tuple (node, previous_parent, previous_size_of_its_root?). Wait, maybe we can design union to only modify one value: Actually, when we union two sets, we attach the root of smaller tree to larger root. This modifies parent[small_root] = large_root; and then sz[large_root] += sz[small_root]. So we modify two values: parent[small_root] and sz[large_root]. So we need to record both. However, we could treat the size change as an update to sz[large_root] and later revert it. So we need two records.
Alternatively, we could use a DSU that doesn't use size but uses random linking and stores height; but still two modifications.
Simpler: we can push onto the stack a pair (changed_node, previous_parent) and then also push (changed_node, previous_size) for the size change, but we need to know which node changed for size. For small root, we change parent; for large root, we change size. So we push two entries: (small_root, old_parent) and (large_root, old_size). When popping, we revert accordingly. But we must know that the first entry corresponds to parent and second to size. However, we can't distinguish just by value. But we could maintain two separate stacks? Actually, we can store a single stack of actions that each contains (node, old_parent, old_size, type) but that's extra memory. Since total number of union operations is small, we can just store a struct with three ints: node, previous value, and a flag indicating whether it's parent (0) or size (1). That's fine.
Better: many implementations use a stack that stores a "snapshot" of the state before the union, like the root that was changed and the previous parent, and they also store the change in size by storing the new root's old size. They often do:
int union(int a, int b) {
a = find(a), b = find(b);
if (a == b) return 0;
if (size[a] < size[b]) swap(a,b);
// now attach b under a
stack.push({b, parent[b], a, size[a]}); // but we need multiple values
parent[b] = a;
size[a] += size[b];
return 1;
}
Then undo: pop the record and revert parent[b] and size[a] to old values. This record contains two nodes and two old values. That's straightforward. So we can define a struct Change { int small; int parent_small; int big; int size_big; }. Or we could store { node1, old1, node2, old2 } and know that node1 is the small root whose parent changed, node2 is the big root whose size changed. Then on undo, revert parent[node1]=old1, size[node2]=old2.
That's fine.
Now, DSU find without path compression:
int find(int x) {
while (parent[x] != x) x = parent[x];
return x;
}
Since depth could be O(n) in worst-case if many unions, but union by size ensures depth O(log n). So find is O(log n). For n=40k, that's okay.
We must also consider that we will call find many times. In the DFS, for each query leaf, we call find(u) and find(v). So total find calls: up to number of queries plus union operations (find within union). So it's okay.
Now we need to ensure the segment tree traversal is efficient: It's a recursive function that goes over all nodes. Since k up to 40k, depth is about 16, recursion is fine.
Now implement:
-
Parse input.
-
Create arrays: ops = vector of tuple<int,int,int> for each i from 1..k.
-
Initialize map< pair<int,int>, int > start_time; (or we can encode edge as 64-bit: u * n + v, but n up to 40k, so u*n+v fits 1.6e9 which fits in 64-bit; or just use map with pair). Since total distinct edges ≤ min( (n choose 2), number of insert operations ), up to 40k, it's fine.
-
Also we'll store vector queries: each with index i, u, v, order (to output in order). Or we can keep answer array sized by number of queries, and map query index to answer. We'll also need to know at leaf i, if it's a query, we answer.
-
After processing ops and building intervals, we also need to collect the intervals for each edge.
Implementation steps:
-
Read n, k.
-
vector ops(k+1) 1-indexed.
-
unordered_map (or map) from pair<int,int> to int active_start. But we need to handle multiple intervals. We'll use a dictionary that maps edge to the most recent insertion time (if currently inserted). Since edges cannot be inserted twice without deletion, there will be at most one active start per edge. So when we see type 1: if edge already in map? The problem says it appears only when there is no passage, so we guarantee it's not already present. So we can just store start[edge] = i.
When we see type 2: we get deletion at i, then we retrieve start = start[edge]; then we add interval (start+1, i-1) if start+1 <= i-1 (since there could be no query between them, but we still add it; it's fine). Then we erase start[edge].
When we see type 3: we record query: queries.push_back({i, u, v, query_index}). We'll maintain query_count as we go, assign answer array.
After loop, for each edge still in start map, add interval (start+1, k) if start+1 <= k.
-
Now we have intervals: we need to store for each interval the edge (u,v). We'll create a list of intervals: each is (l, r, u, v). l and r are inclusive.
However, there might be intervals where l > r (if insertion and deletion are consecutive, e.g., insert at i, delete at i+1 => l = i+1, r = i => l > r). In that case, there is no time point for query, so we can skip adding such interval. So we only add if l <= r.
-
Build segment tree: We'll have a vector<vector> tree; each node holds a list of edges (u,v) that are active for the entire node interval. We'll define segtree size: usually using array of vectors for 4*k.
Function build: we will create a segment tree over range [1, k] (time indices). Then for each interval (l, r, u, v), call add_interval(1,1,k,l,r,edge). In add_interval: if l <= L and R <= r: push edge to node's vector; else if r < L or l > R: return; else recur to children.
-
Then perform DFS: function dfs(node, L, R):
- Save current stack size = dsu.get_stack_size().
- For each edge (u,v) in tree[node]: dsu.unite(u,v).
- If L == R:
- if ops[L].type == 3:
- answer for that query: dsu.find(u) == dsu.find(v) ? YES : NO.
- (We need to map query index to answer. We can store answer array with size = number_of_queries, and for each query we recorded its order. At leaf L, we can store answer[query_order] accordingly.)
- Else:
- mid = (L+R)/2
- dfs(left child, L, mid)
- dfs(right child, mid+1, R)
- dsu.rollback(stack_size) // revert to previous stack size.
-
Output answers in order of queries as they appear in input.
Now, careful about indices: The leaf nodes correspond to each operation index from 1 to k. But for leaves that are not queries, we just do nothing. However, we must still have the DSU state at those leaves? Since we are doing a depth-first traversal, we will apply all edges that cover that leaf. That means at leaf representing an insertion or deletion operation, we will have edges that are active for that time point. But we ensured intervals are only for times that are queries. But it's possible that there is an edge active for that leaf if we included that leaf in interval, but we purposely excluded insertion and deletion times. So they won't be active. But what about other edges? They may be active at that time. However, we don't need to answer queries at those leaves, so it's fine that we apply them and then rollback. It's just that we are applying them for those leaves unnecessarily. But that's okay; it's simpler to traverse all leaves. Alternatively, we could only traverse leaves that are queries, but that would complicate the recursion. So we'll just traverse all.
Now, DSU with rollback: We'll implement as class.
Data structures:
struct DSU {
vector parent, sz;
vector<tuple<int,int,int,int>> history; // small, old_parent_small, big, old_size_big? But we could store only necessary.
// Actually we can store two entries: (node, old_parent) for parent change, and (node, old_size) for size change. But to rollback we need to know which entry corresponds to which.
// I'll use a struct Change { int type; int node; int old_value; };
// type 0: parent, type 1: size.
// We'll push two changes per union.
struct Change {
int type; // 0: parent, 1: size
int node;
int old_val;
};
vector hist;
DSU(int n) {
parent.resize(n);
sz.resize(n, 1);
for (int i=0; i<n; ++i) parent[i]=i;
}
int find(int x) const {
while (parent[x] != x) x = parent[x];
return x;
}
bool unite(int a, int b) {
int ra = find(a);
int rb = find(b);
if (ra == rb) return false;
if (sz[ra] < sz[rb]) swap(ra, rb); // ra is larger
// attach rb under ra
hist.push_back({0, rb, parent[rb]}); // parent change
parent[rb] = ra;
hist.push_back({1, ra, sz[ra]}); // size change
sz[ra] += sz[rb];
return true;
}
int get_stack_size() const {
return hist.size();
}
void rollback(int target_size) {
while (hist.size() > target_size) {
Change ch = hist.back(); hist.pop_back();
if (ch.type == 0) {
parent[ch.node] = ch.old_val;
} else {
sz[ch.node] = ch.old_val;
}
}
}
};
But note: In union, we need to ensure that we push changes only if union happens, so that rollback can revert correctly.
Alternatively, we could push a marker when no union happens, but we don't need to because we only push on union.
Edge Cases:
-
n up to 40000, but vertices are 0-indexed.
-
k up to 40000.
-
The number of intervals: each insertion leads to either an interval if later deletion or end. So intervals ≤ number of insertions, ≤ k.
-
The segment tree building: we need to add intervals to nodes. For each interval we add edge to O(log k) nodes. That's fine.
Now memory: tree vector for segment tree: 4 * k vectors of edges. Each vector may hold edges. Total edges added across nodes is O(m log k) where m is number of intervals. m ≤ 40000, log k ~16, so about 640k edges stored. Each edge is two ints (u,v). So memory ~ 640k * 8 bytes? maybe plus overhead of vector, but okay.
Potential issues: The segment tree recursion might be deep, but depth is ~16, so fine.
Now we need to be careful about the mapping of query indices to answer order. Since queries may appear in any order, we should assign each query a sequential id as we read them. Then at leaf, we need to know which query id corresponds to that index (if any). One way: store an array query_at[i] that contains (query_id, u, v) if type 3, else empty. So after reading, we can fill query_at[i] = {query_id, u, v} for query ops. Then during DFS at leaf i, if query_at[i] exists, we answer.
Implementation Steps in code:
int main() {
int n, k;
cin >> n >> k;
vector<tuple<int,int,int>> ops(k+1); // 1-indexed: type, u, v
vector<pair<int,int>> queries_at(k+1, {-1,-1}); // if query, store u,v; else -1. And we also need query id; we can store an additional vector query_id_at
vector<int> query_id_at(k+1, -1);
int qcnt = 0;
map<pair<int,int>, int> start; // active insertion time for edge
for (int i=1; i<=k; ++i) {
int t, u, v;
cin >> t >> u >> v;
ops[i] = {t, u, v};
if (t == 1) {
// insertion
start[{u, v}] = i;
} else if (t == 2) {
// deletion
auto it = start.find({u, v});
assert(it != start.end());
int l = it->second + 1;
int r = i - 1;
if (l <= r) {
// We'll collect intervals in a list
// Actually we need to store intervals for later addition to segment tree.
// So we need a list of intervals.
// Let's declare vector<Interval> intervals; outside loop.
// We'll add later.
intervals.push_back({l, r, u, v});
}
start.erase(it);
} else { // t == 3
queries_at[i] = {u, v};
query_id_at[i] = qcnt++;
}
}
// after loop, handle remaining active edges
for (auto &[edge, s] : start) {
int l = s + 1;
int r = k;
if (l <= r) {
intervals.push_back({l, r, edge.first, edge.second});
}
}
// Build segment tree over [1, k]
int N = k;
vector<vector<pair<int,int>>> segtree(4*N + 5); // each node holds list of edges (u,v)
// function to add interval
auto add_interval = [&](int node, int L, int R, int ql, int qr, int u, int v) {
if (ql > R || qr < L) return;
if (ql <= L && R <= qr) {
segtree[node].emplace_back(u, v);
return;
}
int mid = (L + R) / 2;
add_interval(node*2, L, mid, ql, qr, u, v);
add_interval(node*2+1, mid+1, R, ql, qr, u, v);
};
for (auto &inter : intervals) {
int l = inter.l, r = inter.r, u = inter.u, v = inter.v;
add_interval(1, 1, N, l, r, u, v);
}
// DSU with rollback
DSU dsu(n);
vector<string> answers(qcnt); // store "YES"/"NO"
// DFS traversal
function<void(int,int,int)> dfs = [&](int node, int L, int R) {
int snapshot = dsu.get_stack_size();
// apply edges at this node
for (auto &[u, v] : segtree[node]) {
dsu.unite(u, v);
}
if (L == R) {
// leaf: if this is a query, answer
if (queries_at[L].first != -1) {
auto [u, v] = queries_at[L];
bool connected = (dsu.find(u) == dsu.find(v));
answers[query_id_at[L]] = connected ? "YES" : "NO";
}
} else {
int mid = (L + R) / 2;
dfs(node*2, L, mid);
dfs(node*2+1, mid+1, R);
}
// rollback
dsu.rollback(snapshot);
};
dfs(1, 1, N);
// output answers in order
for (auto &ans : answers) cout << ans << '\n';
return 0;
}
Now check the example:
4 10
1 0 1
1 0 2
3 1 2
2 0 1
1 2 3
3 0 1
1 0 1
2 0 2
1 1 3
3 0 2
Let's manually trace intervals:
ops:
1: ins (0,1) -> start[(0,1)] = 1
2: ins (0,2) -> start[(0,2)] = 2
3: query (1,2) -> need answer: at this point, edges: (0,1) and (0,2) are present, so 1 and 2 connected via 0 -> YES.
4: del (0,1) -> interval for (0,1): l=1+1=2, r=4-1=3 -> [2,3]. Check: l=2 <= r=3. So this edge active for times 2,3. (time indices 2 and 3). time 2 is insertion of (0,2)? Actually time 2 is operation 2 which is insertion; but our intervals only for queries. But we include time 2? However, time 2 is not a query, but that's okay, it will be considered active at leaf 2 during DFS, but we don't care. However, is this correct? At time 2, after operation 2, the edge (0,1) is still present? Actually after operation 2 (insertion of (0,2)), the edge (0,1) is still present because it hasn't been deleted. So at time 2 (which is an insertion operation), the edge is present. But we didn't include time 2 in the active interval? Wait, our active interval for (0,1) is [2,3]. So leaf 2 (operation index 2) will have (0,1) active according to our model. But is that correct? Let's think: At time 2, after processing operation 2, if we were to ask a query (but there is none), the state would include (0,1). So it's fine that we treat it as active at leaf 2, even though it's not a query. There's no harm. So it's okay.
But careful: At time 2, we also have insertion of (0,2). The interval for (0,2) will be later: It gets deleted at operation 8? Actually (0,2) is deleted at operation 8 (2 0 2). So its interval: start at operation 2, so l = 2+1 = 3, r = 8-1 = 7 -> [3,7]. So (0,2) is active from time 3 to 7 inclusive. So at leaf 2, (0,2) is not yet active (since after operation 2 it's present, but according to our mapping, active starting at time 3? That seems inconsistent. Let's examine: Operation 2 is insertion of (0,2). After insertion, the edge becomes present. So at any time after operation 2, before deletion, it is present. So for a query at time 3 (the query operation at index 3), it should see (0,2). Indeed our interval [3,7] includes time 3, correct. But what about time 2? If there were a query at time 2 (right after insertion), would it see (0,2)? Time 2 is the operation itself, but query at time 2 would be after operation 2? Actually if there is a query at index 2, that would be the operation type 3 at index 2. But there is no query. However, suppose there were a query at index 2, would it see (0,2)? The order: operation 1 executed, then state. Then operation 2: if it's a query, we would answer based on state after operation 1, because the query is operation 2 itself and we haven't applied insertion yet. Wait: That's a nuance: In dynamic connectivity offline problems, it's typical to consider the state after processing previous operations. That is, when we have a query at index i, we consider all operations before i. So the insertion at index i does not affect a query at index i. So our mapping of active intervals should reflect that: an edge inserted at time i becomes active for queries at times > i, not including i. So our mapping of (ins+1, del-1) is correct for queries. But for leaves that are not queries, it's okay if we erroneously treat the edge as active at time i, but that might affect other leaves? Actually, the segment tree DFS processes leaves sequentially in order of indices (the recursion is depth-first, which goes from left to right if we do left child then right child). The order of visiting leaves is in-order: we go to leftmost leaf first, then next, etc. That is essentially time order. So when we are at leaf i, we apply all edges that are active for that leaf. Then we answer query if needed, then roll back those edges before moving to next leaf? Wait, the recursion: At node [L,R], we first apply edges for that node. Then if it's not leaf, we recursively go to left child, then right child. After returning, we rollback. So the state when we are at leaf i includes all edges from nodes on the path from root to leaf i that have intervals covering leaf i. But note: we apply edges at each node as we go down. Since we never rollback until after processing both children, the edges from a parent node remain applied throughout the processing of its whole subtree. So the state at leaf i is the union of all edges from nodes whose intervals contain i (i.e., edges that are active for the whole node interval, but the node interval may be larger than just i, but we apply them at the node and they persist for entire subtree). So the state at leaf i represents exactly the set of edges that are active for the whole interval of that node, but because the node interval is a superset, it ensures that the edge is active for all times in that subtree, including leaf i. However, if an edge's active interval is [l, r] and we add it to nodes that fully cover subsegments of [l,r], then the edge will be applied at those nodes and will be present for all leaves in that node's range. So at leaf i, if i is within [l,r], the edge will be present; otherwise not. So the mapping works as expected.
Now consider the active interval for (0,2) we set as [3,7]. That means at leaf 2, (0,2) should NOT be present. But is that correct according to the problem? If there were a query at time 2, it would not see (0,2) because insertion occurs at time 2, and the query would be processed before that insertion (since query is operation 2). In our timeline, operation 2 is the insertion itself, not a query. So there is no query at time 2. So it's fine that (0,2) is not active at leaf 2. But what about leaf 3? leaf 3 is a query. (0,2) is active at leaf 3, correct.
Now consider (0,1) interval: [2,3]. So leaf 2 will have (0,1) active; leaf 3 will have (0,1) active. But at time 2, is (0,1) active? After operation 1 (insert (0,1)), then operation 2 occurs (insert (0,2)). The state before operation 2 includes (0,1). So if there were a query at time 2, it would include (0,1). So leaf 2 includes (0,1), correct. But leaf 3: after operation 2, state includes (0,1) until deletion at operation 4. So leaf 3 (query at time 3) includes (0,1), correct. So intervals are consistent.
But wait, check (0,1) interval ends at 3, but deletion occurs at operation 4. So after operation 4, (0,1) is removed. So leaf 4 is deletion operation. There is no query at leaf 4, but if there were a query at leaf 4, would (0,1) be present? Operation 4 is deletion. The state before processing operation 4 includes (0,1). So query at leaf 4 (if it existed) would see (0,1) because query occurs before deletion. However, our interval [2,3] does NOT include 4, so leaf 4 would not have (0,1). That would be incorrect if there were a query at leaf 4. But note: In our mapping, we set l = ins+1, r = del-1. That excludes the deletion time itself. But if there were a query at the same index as a deletion, that would be impossible because deletion operation is type 2, not query. So there is never a query at a deletion index. So it's fine that leaf 4 does not have (0,1). So the mapping works.
But there is a nuance: what about a query that appears immediately after a deletion? For example, suppose deletion at index i, then query at index i+1. Our mapping: deletion at i, so the edge is removed after i. So for query at i+1, it should not see the edge. Our interval ends at i-1, so leaf i+1 is after the interval, so correct.
Thus the mapping is correct.
Now back to example: intervals:
(0,1): [2,3]
(0,2): from start 2, delete at 8? Actually we have deletion at operation 8: "2 0 2". So (0,2) interval: l=3, r=7
(2,3): inserted at operation 5: "1 2 3", and not deleted? Actually later? There's insertion at operation 9: "1 1 3" and then query at 10. But (2,3) is not explicitly deleted. So its interval: l=5+1=6, r=10? Wait k=10, so r=10. So [6,10].
(0,1) again: inserted at operation 7: "1 0 1", and later maybe not deleted? It is not deleted later; we have operation 8 deletion of (0,2), operation 9 insertion (1,3), operation 10 query. So (0,1) second interval: l=7+1=8, r=10. So [8,10].
(1,3): inserted at operation 9: l=9+1=10, r=10. So [10,10].
Now queries:
Operation 3: query (1,2) at time 3. State: edges active at time 3: (0,1) from first interval (2-3), (0,2) from interval (3-7). So both present. So connectivity: 1 and 2 both connect to 0 -> YES.
Operation 6: query (0,1) at time 6. State: active edges: (0,2) [3-7] present, (2,3) [6-10] present, (0,1) first interval ended at 3, second not yet started (starts at 8). So (0,1) not present. Also (0,1) not inserted again until operation 7. So at time 6, edge (0,1) does not exist. Are 0 and 1 connected? Possibly via other paths: 0-2-3? But 3 is not connected to 1. So no. So answer NO.
Operation 10: query (0,2) at time 10. State: edges: (2,3) active [6-10], (0,1) active [8-10], (1,3) active [10-10]. Also (0,2) is deleted at 8, so not active. So we have vertices: edges: 0-1, 1-3, 3-2. So 0 connected to 2 via 0-1-3-2? 0-1, 1-3, 3-2 gives path 0-2, so yes connected. So answer YES.
Matches output: YES, NO, YES.
Now our algorithm should produce that.
Now we need to ensure that we handle edges correctly: For each interval we store (l, r, u, v) and add to segtree.
One more nuance: In offline approach, we also need to consider that edges may be inserted and deleted multiple times. Our handling with map start works.
Now implementation details:
-
Use map or unordered_map for edge start. Since edges are up to 40k, we can use unordered_map with custom hash for pair<int,int>. Or we can use map (ordered) which is fine (log factor). But we can also encode as long long: ( (long long)u << 20 ) + v? Actually n up to 40000, so we can encode as (u * 40001LL + v) or (u * n + v). Since n is up to 40000, product up to 1.6e9, fits in 32-bit? 40000*40000=1.6e9, fits in signed 32-bit? 2^31-1 = 2.147e9, so it's okay. But careful: u * n + v could overflow 32-bit if n=40000 and u=39999 -> 1.59996e9, safe. However, we also need to store negative? No. So we could use int key. But using pair is fine.
-
For segment tree, we need to allocate vector of vectors. Since total edges added is O(m log k), and m ≤ k, say up to 40000 * log2(40000) ~ 4000016 = 640k, each vector may have some overhead. We'll allocate segtree as vector<vector<pair<int,int>>> tree(4N+5). For each node, vector will be empty initially. Then we call add_interval recursively. It's fine.
-
DSU with rollback: we must implement find as non-recursive loop to avoid recursion depth issues. Since tree depth is limited, okay.
Potential pitfalls:
-
In DSU unite, we should ensure we attach the smaller tree to larger to guarantee log N depth. The size after union: ra's size increases. We push changes: first change parent of rb, then change size of ra.
-
However, when we rollback, we need to revert in reverse order. Since we push parent change then size change, when we pop, we will revert size change first (since stack LIFO) then parent change. That is fine: we need to revert size before parent? Actually if we revert parent first, it's okay as long as we revert both to old values. But order may matter if we later call find during rollback? But rollback is done at a moment when we are not using DSU for queries; after rolling back, we return to parent node. The order of reverting does not matter as long as both are reverted to correct values. So it's fine.
But we must be careful: In DSU find, we rely on parent pointers. If we revert size before parent, temporarily the size may be inconsistent but parent still pointing to ra; but after parent reverted, it's fine. Since no queries are performed between popping the two changes (they are popped consecutively), it's safe.
Alternatively, we could push a single compound change. I'll go with the two-change approach for simplicity.
- DSU stack size: we track number of changes. The get_stack_size() returns hist.size(). rollback(target) pops until size == target.
Now complexity: O((n + k log k) α(n)? Actually without path compression, union/find are O(log n). So overall O((m log k) * log n + q log n). With n,k up to 40k, fine.
Edge Cases:
-
n may be as large as 40000, but we need DSU of size n.
-
There may be no queries; then output nothing. That's fine.
-
Intervals may have l > r; we skip.
-
The segment tree range is [1,k]. But what if there are queries at time 1? Can there be a query at the very first operation? Possibly. Then what edges are active? None, because any insertion would be at time 1 if it's an insertion, but query at time 1 would be before any insertions. So connectivity false unless u==v but u<v so always distinct? Actually u<v, so always different vertices. So answer NO. Our intervals: For an insertion at time 1, l = 2, so not covering time 1. So DSU will be empty at leaf 1. So answer will be NO if query at time 1. That's correct.
-
Also, note that there could be queries at time indices where no intervals cover; that's fine.
Now we must be careful about recursion depth in DFS: The segment tree recursion depth is O(log k) ~ 16, but the DFS traversal calls recursively on children; the maximum depth of recursion is also O(log k) because we go down the tree? Actually the DFS function calls itself recursively for left and right children, but it's not tail recursion; the call stack depth could be as deep as the height of the tree times the number of recursive calls? Since we call dfs on left child, then on right child, but these are nested: the call to left child returns before calling right child. So the maximum depth of recursion is the height of the tree (since each call goes deeper, then returns). So depth ~ O(log k). So safe.
Now let's test with example manually via code mentally.
Now, about reading input: The input is small, we can use cin.
Potential memory: segment tree vectors: 440000 = 160k nodes. Each node has a vector; that's 160k vectors, each maybe small. That could be heavy? Actually 160k vectors each with small overhead (like 24 bytes) could be about 4 MB overhead, plus stored edges. But each node will have some edges. However, 160k vectors might be a lot and could cause memory issues? Let's calculate: 4N is about 160k. Each vector typically has a small fixed overhead (e.g., 24 bytes on 64-bit). 160k * 24 = 3.84 MB, which is acceptable. Additionally, edges storage: up to 640k edges, each edge is two ints, stored in vectors. Each stored edge is a pair of ints (8 bytes) plus overhead in vector (but vector stores elements contiguously, so only the pair objects). So edges storage ~ 640k * 8 = 5.12 MB. So total maybe < 10 MB, plus DSU arrays, etc. So fine.
But we could reduce nodes to exactly 4*N, but that's fine.
Alternatively, we can use a segment tree with size next power of two, but not necessary.
Now about implementation in C++: Use standard types.
Now verify with sample.
Now check for correctness of DSU find: It should be const or not? In unite we call find, which traverses parent. But since we may have path not compressed, find is O(depth). That's fine.
Now handle the case when u==v? Not possible because u<v in input, so always distinct.
Now output: each answer on new line.
Now think about possible pitfalls: The map for start times: we used map<pair<int,int>, int>. When we delete, we need to ensure we find the correct start. The problem guarantees that when deletion appears, there is a passage present, so it should be in the map. But we need to be careful about edges that were inserted multiple times: The map will have the most recent insertion start. That's correct because the edge is present.
Now what about an edge being inserted again after being deleted? After deletion we erase it from map, so later insertion will create a new entry. So start times are independent.
Now what about intervals where l > r? We skip.
Now we must also consider that operations are given in chronological order, and we process them sequentially to build intervals. But note: There could be an insertion of edge (u,v) at time i, then a query at same time i? No, because each line is one operation. So cannot be both.
Now potential bug: In DSU unite, we call find. But find is not path compressed, so it's okay. However, during the DFS, we may have many unions. The depth of trees could become large if we always attach without considering size? But we do union by size, so depth is O(log n). Good.
Now let's think about rollback: When we rollback, we need to revert the DSU to exactly the state before entering the node. Since we saved snapshot size before applying node's edges, we rollback to that size. That will revert all unions done in this node and also any unions done in its children (because children will have rolled back themselves). So it works.
Now answer extraction: At leaf L, we have queries_at[L] maybe. We use query_id_at[L] to index answers. We'll store answers as strings.
Now output in order of queries appearance.
Now test with a simple case:
n=2, k=2
1 0 1
3 0 1
Processing:
ops: 1: ins (0,1) start[(0,1)]=1
2: query (0,1) record query id=0 at time2.
After loop: remaining edge (0,1) with start=1, l=2, r=2 (since k=2). So interval [2,2] added.
Segment tree: add edge to node covering [2,2].
DFS:
- root [1,2] apply? (no edges at root)
- left child [1,1] no edges. leaf1: no query.
- right child [2,2]: at node covering [2,2], apply edge (0,1) => DSU union 0 and1. leaf2: query => find same root => YES.
- rollback.
Works.
Another test: n=2, k=3
1 0 1
2 0 1
3 0 1
Processing:
op1: ins, start[(0,1)]=1
op2: del, get start=1, l=2, r=1? Since i=2, l=2, r=1 => l>r, skip interval.
erase start.
op3: query at time3. No remaining edges. So answer NO.
Works: interval skipped, so edge not added anywhere. At leaf3, no edge, answer NO.
Now test: insertion and deletion with query between: n=2, k=3
1 0 1
3 0 1
2 0 1
Processing:
op1: ins start=1
op2: query at time2 => record query id0
op3: del, get start=1, l=2, r=2? i=3, l=2, r=2 => interval [2,2] added.
So edge active at leaf2. So answer YES. Then at leaf3 (deletion) no query. Works.
Now test multiple intervals for same edge: n=2, k=5
1 0 1
3 0 1
2 0 1
1 0 1
3 0 1
Processing:
op1: ins start=1
op2: query id0 at time2
op3: del: start=1, l=2, r=2? i=3 => l=2, r=2 -> interval1 [2,2] (active at time2). erase.
op4: ins start=4
op5: query id1 at time5
After loop: remaining edge start=4, l=5, r=5 -> interval2 [5,5]
Now intervals: first [2,2], second [5,5].
DFS: leaf2 gets edge from interval1 => answer YES. leaf5 gets edge from interval2 => answer YES.
Works.
Now test where there is query at time just after deletion: n=2, k=4
1 0 1
2 0 1
3 0 1
Processing:
op1: ins start=1
op2: del: start=1, l=2, r=1? i=2 => l=2, r=1 -> skip (no interval)
op3: query id0 at time3.
No remaining edges. So answer NO. Works.
Now we need to think about the order of operations: In DFS we process leaves in order, but do we guarantee that the DSU state at leaf i reflects the set of edges active at that time? Let's reason: For each edge, we add it to segment tree nodes covering its active interval. When we traverse the segment tree recursively, we apply edges at a node before traversing its children. Since the node's interval covers the entire subtree, the edge will be applied for all leaves in that subtree. This matches the fact that the edge is active for all times in that interval. So state at leaf i will include all edges whose active intervals contain i. That's exactly the set of edges active at time i (for queries). So it works.
Now about queries at leaves that are not queries: they will also have state but we ignore. That's fine.
Now about DSU with rollback: We need to ensure that find does not modify the structure, because we need to be able to rollback to previous states. Since we don't use path compression, find is read-only, fine.
Now implementation details:
We'll need to store intervals while reading operations. We can't add intervals to segtree before we've read all operations because we need to know all intervals. So we first read all ops, collect intervals and queries in one pass. Then build segtree and DFS.
But note: For intervals we need to know the final k (total ops). That's known from input.
Now code skeleton:
#include <bits/stdc++.h>
using namespace std;
struct DSU {
vector parent, sz;
struct Change {
int type; // 0: parent, 1: size
int node;
int old_val;
};
vector hist;
DSU(int n) : parent(n), sz(n, 1) {
for (int i = 0; i < n; ++i) parent[i] = i;
}
int find(int x) const {
while (parent[x] != x) x = parent[x];
return x;
}
bool unite(int a, int b) {
int ra = find(a);
int rb = find(b);
if (ra == rb) return false;
if (sz[ra] < sz[rb]) swap(ra, rb);
// attach rb under ra
hist.push_back({0, rb, parent[rb]});
parent[rb] = ra;
hist.push_back({1, ra, sz[ra]});
sz[ra] += sz[rb];
return true;
}
int getSize() const {
return hist.size();
}
void rollback(int target) {
while (hist.size() > target) {
Change ch = hist.back();
hist.pop_back();
if (ch.type == 0) parent[ch.node] = ch.old_val;
else sz[ch.node] = ch.old_val;
}
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, k;
cin >> n >> k;
// ops not needed after processing, but we need to know type for query mapping
vector<int> opType(k+1);
vector<pair<int,int>> opUV(k+1);
vector<pair<int,int>> queries_at(k+1, {-1,-1});
vector<int> query_id_at(k+1, -1);
int qcnt = 0;
map<pair<int,int>, int> start; // start time of insertion
vector<tuple<int,int,int,int>> intervals; // l, r, u, v
for (int i = 1; i <= k; ++i) {
int t, u, v;
cin >> t >> u >> v;
opType[i] = t;
opUV[i] = {u, v};
if (t == 1) {
start[{u, v}] = i;
} else if (t == 2) {
auto it = start.find({u, v});
// guaranteed exists
int l = it->second + 1;
int r = i - 1;
if (l <= r) {
intervals.emplace_back(l, r, u, v);
}
start.erase(it);
} else { // t == 3
queries_at[i] = {u, v};
query_id_at[i] = qcnt++;
}
}
// remaining active edges
for (auto &[edge, s] : start) {
int l = s + 1;
int r = k;
if (l <= r) {
intervals.emplace_back(l, r, edge.first, edge.second);
}
}
// Build segment tree
int N = k;
vector<vector<pair<int,int>>> segtree(4*N + 5);
function<void(int,int,int,int,int,int,int)> add_interval = [&](int node, int L, int R, int ql, int qr, int u, int v) {
if (ql > R || qr < L) return;
if (ql <= L && R <= qr) {
segtree[node].emplace_back(u, v);
return;
}
int mid = (L + R) / 2;
add_interval(node*2, L, mid, ql, qr, u, v);
add_interval(node*2+1, mid+1, R, ql, qr, u, v);
};
for (auto &[l, r, u, v] : intervals) {
add_interval(1, 1, N, l, r, u, v);
}
DSU dsu(n);
vector<string> answers(qcnt);
function<void(int,int,int)> dfs = [&](int node, int L, int R) {
int snap = dsu.getSize();
for (auto &[u, v] : segtree[node]) {
dsu.unite(u, v);
}
if (L == R) {
if (queries_at[L].first != -1) {
auto [u, v] = queries_at[L];
bool conn = (dsu.find(u) == dsu.find(v));
answers[query_id_at[L]] = conn ? "YES" : "NO";
}
} else {
int mid = (L + R) / 2;
dfs(node*2, L, mid);
dfs(node*2+1, mid+1, R);
}
dsu.rollback(snap);
};
dfs(1, 1, N);
for (auto &ans : answers) {
cout << ans << '\n';
}
return 0;
}
Now test with sample.
But there is a nuance: We used map<pair<int,int>,int> start. For edge (u,v) we store as (u,v) with u<v. In input, u<v is guaranteed. So we don't need to normalize order. In type 2, they also give u<v, so it's consistent. So fine.
Now check for correctness when there are duplicate intervals for same edge? Not overlapping.
Now let's test with sample manually by running mental simulation or quick code check.
Now think about the recursion depth of the add_interval function: It will be called recursively for each interval, depth O(log k). That's fine.
Now memory: segtree vector of vectors of edges. add_interval pushes edges into nodes. After building, we call dfs.
Potential improvements: Use iterative segment tree? Not needed.
Now confirm that DSU rollback correctly handles the case where unite returns false (already connected). In that case we push nothing, so rollback works.
Now think about the size of DSU history: In worst case, number of unite calls = total number of edges added to nodes. That's up to ~ 640k. Each unite pushes 2 changes, so history size up to 1.28M. That's fine.
Now one more nuance: In DSU find, we use const find, but inside unite we modify parent and size. That's fine.
Now about reading: we use cin >> t >> u >> v. Ensure we read as int.
Now about output: should be uppercase YES/NO.
Now think about constraints: n up to 40000, but we also need to be careful about recursion in add_interval? The recursion depth is O(log k) ~ 16, so fine.
Now test with a small random case to ensure logic.
But there is a potential issue: In DSU, find uses while loop, but if the tree depth becomes large due to many unions (max depth about log2(40000) ~ 16), that's okay.
Now about the segment tree building: we used 4N+5, which is safe. However, if N=1, then 41+5=9, fine.
Now for N=40000, 4*40000=160000, plus 5.
Now consider that some intervals may have l and r that are out of range [1,k]? l is at least 2, r at most k. So within range.
Now about memory for segtree: For each node we have a vector. In the worst-case, if we add each interval to many nodes, the total number of stored edges is O(m log k). That's fine.
Now possible bug: In DFS, we call dsu.find(u) and dsu.find(v). But note that u and v may be same? Not possible as per input. Good.
Now let's think about the correctness of the mapping for intervals: I want to double-check with a scenario where there is an insertion at time i and a query at time i (which doesn't happen). So fine.
Now consider the scenario: Insert at time 1, delete at time 2, query at time 2? Not possible because time 2 is deletion. So fine.
Now consider scenario: Insert at time 1, query at time 2, delete at time 3. Our interval [2,2] includes query at time 2. Good.
Now scenario: Insert at time 1, query at time 1? Not possible.
Now scenario: Insert at time 1, query at time 3, delete at time 2. That would be out of order because deletion must happen after insertion, and query at time 3 after deletion. But that's possible: 1: ins, 2: del, 3: query. Our interval for insertion: l=2, r=1 => skip, so no edge at query, correct.
Now scenario: Insert at time 1, insert again at time 2? Not allowed.
Now scenario: Delete at time 1? Not allowed because not present.
Now everything seems consistent.
Now about performance: The DFS will traverse all nodes, but we only need to process leaves that are queries. However, traversing all nodes is fine; total nodes ~ 2*N. So O(N) traversal.
Now one more thing: We used map for start. Might be okay but unordered_map could be faster. However, k=40k, map log factor is negligible.
But there is a subtlety: In the offline algorithm, we treat each operation index as leaf. However, in segment tree, we assign leaves to each time point. If there are many operations (40k) and we have to traverse leaves that are not queries, we still apply edges for those leaves. This could cause extra work: At leaf i that is not a query, we still call dsu.unite for edges active at i, but we don't need to answer. However, those unions will be rolled back after leaving the leaf's node? Wait, the leaf is processed inside the DFS. At leaf L, we are at a node that covers only that leaf (since L==R). We apply edges for that leaf's node (i.e., edges that have intervals covering L and were added to that node). But note: The way we add intervals to segment tree: For an interval [l,r], we add it to nodes that fully cover subsegments, not to every leaf individually. In the DFS, when we reach leaf L, we have applied all edges from all nodes on the path from root to leaf. Those edges are active for the whole interval of those nodes, which includes L. So at leaf L, the DSU state contains all edges whose intervals contain L. That's correct. But if L is not a query, we still have this state, but we do nothing. Then we rollback to the snapshot taken at the beginning of the node (which was after applying edges for that node? Actually snapshot is taken before applying the node's own edges. But the node's own edges are applied at the beginning of dfs(node). For leaf node, we apply its edges (which are edges whose intervals exactly match this leaf? Actually the leaf node may have edges added directly if the interval covers exactly that leaf, but also edges from ancestor nodes are already applied because they were applied at those ancestor nodes and not rolled back until after the subtree. So the snapshot at leaf node's start only captures the state before applying the leaf's own edges, but the ancestor edges are still present. So at leaf L, the DSU state includes all edges from ancestors (which cover larger intervals) plus edges from leaf node (which cover leaf). After we process leaf, we rollback to snapshot, which will undo only the leaf node's edges, but ancestor edges remain? Actually the dfs function for leaf node: snapshot = dsu.getSize() at beginning of function. Then we apply leaf node's edges. Then we answer query (or not). Then we rollback to snapshot, removing only the leaf node's edges. But the ancestor edges were applied in parent nodes, and those parent nodes have their own snapshots and will rollback later when returning from those parent nodes. So overall, the state for leaf L includes all edges from all nodes on the path. That's correct. But if L is not a query, we still apply leaf node's edges (which are those intervals that were added to this leaf node) and then roll them back immediately after leaf. That is extra work but not too much.
But note: In segment tree construction, intervals are added to nodes that fully cover a segment. So for a leaf node, the only intervals that would be added to that leaf are those intervals that exactly match the leaf? Actually if an interval [l,r] covers leaf L, it might be added to some ancestor node that covers a range including L, not necessarily to the leaf node. For example, if interval is [2,5], it might be added to a node covering [2,3] if that node is fully inside [2,5], but not to leaf 2 individually. So leaf nodes may have no edges stored at all. In that case, we still do snapshot and rollback but no work. So overhead minimal.
Thus the DFS approach is fine.
Now what about recursion stack for DFS? The maximum depth of recursion is the height of the segment tree (log2(N) ~ 16) for the call chain from root to leaf, plus the recursion for left/right siblings? Actually the recursion is like a depth-first traversal; the maximum recursion depth is when we go from root to leaf and then return. That's O(height) ~ 16. So safe.
Now consider the possibility of large recursion if we implement add_interval recursively. That's also O(log N) depth.
Now all set.
But before finalizing, check for potential bug: In DSU find, we used const method, but parent is not const, but it's okay.
Now there is a nuance: In the DSU rollback, we revert to snapshot. But if we have nested calls, we need to ensure that each node's snapshot is taken before applying its edges. That's what we do.
Now confirm with a more complex scenario where multiple intervals overlap.
Now let's test with a small random sequence by writing a brute-force simulation and compare with offline solution for small n and k, but here we can't run, but we trust.
Now think about time limit: k up to 40k, O(k log k) operations, each union O(log n), total maybe a few million operations, should be fast.
Now potential optimization: Use integer keys for edges via encoding to avoid pair in map. But not needed.
Now we must also consider the possibility that the same edge appears in different intervals, and we add each interval separately. That's correct.
Now final step: Write code.
But one more nuance: The DSU find is O(log n) but could be O(n) in worst-case if we don't use union by size properly? But we use union by size, so depth is at most log2(n) ≈ 16. So fine.
Now about input: u and v are 0-indexed, we store as int.
Now let's ensure we handle the case when there are no queries: qcnt = 0, answers empty, output nothing. That's fine.
Now implement.
Potential bug: In the DFS, when L==R, we use queries_at[L] to get u,v. But note: queries_at[L] is pair<int,int> we initialized to {-1,-1} for non-queries. We set it to {u,v} for query. So check first != -1. But it could be that u=0, so first is 0, not -1, so condition fails. That's a bug: We used -1 as sentinel, but u could be 0, so we need a separate flag. So better to use a boolean array is_query[i] or store query info in separate structure. Let's adjust: We can store for each index i: if it's a query, we store a struct with u,v and query id. Otherwise, we store something else. We can use a vector of optional.
Simplify: Create arrays: query_u[i], query_v[i], query_id[i] where query_id[i] = -1 if not query. That's easier. So we have:
vector query_u(k+1), query_v(k+1), query_id(k+1, -1);
When we encounter query: query_u[i]=u; query_v[i]=v; query_id[i]=qcnt++;
Then in leaf: if (query_id[L] != -1) { bool conn = dsu.find(query_u[L]) == dsu.find(query_v[L]); answers[query_id[L]] = conn ? "YES" : "NO"; }
That avoids sentinel -1 for u.
So update code accordingly.
Now fix.
Now about intervals: we stored as tuple. In C++ we can use struct or tuple. For readability, we can define:
struct Interval { int l, r, u, v; };
vector intervals;
But tuple is fine.
Now rewrite with arrays.
Now code finalization.
Check for minor details: In DSU getSize() we use hist.size() which returns size_t, we cast to int but okay.
Now we need to ensure that we include necessary headers: iostream, vector, map, functional (for recursion). using namespace std; is okay.
Now let's produce final answer.
But before that, consider the possibility of stack overflow due to recursion in dfs if we use recursion on segment tree with large N (40k) but recursion depth is small, so fine. However, some judges may have default stack size limited, but depth ~16 is fine.
Now produce final answer.
One more check: When we add intervals to segment tree, we used function add_interval defined recursively capturing many variables. It's fine.
Now about map iteration after loop: for (auto &[edge, s] : start) { ... } This uses C++17 structured binding. Should be okay for typical online judges that support C++17. If not, we can use old style: for (auto it : start) { int l = it.second+1; ... } But we can assume C++17.
Now final code.
Let's also consider that n may be up to 40000, and we are using 0-indexed DSU.
Now produce final answer.
After final code, test with sample.
We'll now mentally simulate with sample to ensure mapping and arrays correct.
Sample input:
4 10
1 0 1
1 0 2
3 1 2
2 0 1
1 2 3
3 0 1
1 0 1
2 0 2
1 1 3
3 0 2
Processing:
Initialize arrays size 11 (index 1..10).
qcnt=0.
i=1: t=1, u=0, v=1. start[(0,1)]=1. query_id[1]=-1.
i=2: t=1, u=0, v=2. start[(0,2)]=2.
i=3: t=3, u=1, v=2. query_u[3]=1, query_v[3]=2, query_id[3]=0; qcnt=1.
i=4: t=2, u=0, v=1. it= start[(0,1)]=1, l=2, r=3. l<=r => intervals.push_back(2,3,0,1). erase start[(0,1)].
i=5: t=1, u=2, v=3. start[(2,3)]=5.
i=6: t=3, u=0, v=1. query_id[6]=1; query_u[6]=0, query_v[6]=1; qcnt=2.
i=7: t=1, u=0, v=1. start[(0,1)]=7.
i=8: t=2, u=0, v=2. it= start[(0,2)]=2, l=3, r=7 => intervals.push_back(3,7,0,2). erase start[(0,2)].
i=9: t=1, u=1, v=3. start[(1,3)]=9.
i=10: t=3, u=0, v=2. query_id[10]=2; query_u[10]=0, query_v[10]=2; qcnt=3.
After loop: start has entries: (2,3) s=5, (0,1) s=7, (1,3) s=9. For each:
- (2,3): l=6, r=10 -> intervals.push_back(6,10,2,3)
- (0,1): l=8, r=10 -> intervals.push_back(8,10,0,1)
- (1,3): l=10, r=10 -> intervals.push_back(10,10,1,3)
Now intervals list:
1: (2,3,0,1)
2: (3,7,0,2)
3: (6,10,2,3)
4: (8,10,0,1)
5: (10,10,1,3)
Segment tree built accordingly.
DFS:
Will produce answers at leaves 3,6,10. We'll check connectivity.
At leaf 3: active edges: intervals covering 3: (2,3) from interval1 (since 2-3 includes 3) and (3,7) from interval2 (since 3-7 includes 3). So edges (0,1) and (0,2). DSU: union(0,1) and union(0,2) -> all 0,1,2 connected. query (1,2) -> YES.
At leaf 6: active edges covering 6: (3,7) includes 6 -> (0,2); (6,10) includes 6 -> (2,3); (maybe others? (2,3) from first interval is 2-3 not include 6, (8,10) not, (10,10) not). So edges: (0,2) and (2,3). Union: after unions, 0-2-3 connected. But (0,1) not present. Query (0,1) -> 0 and 1 not connected. So NO.
At leaf 10: active edges covering 10: (6,10) includes 10 -> (2,3); (8,10) includes 10 -> (0,1); (10,10) includes 10 -> (1,3). So edges: (2,3), (0,1), (1,3). Unions: first unite (2,3): sets {2,3}. Then unite (0,1): set {0,1}. Then unite (1,3): find(1)=0 (since 0 and 1 are together), find(3)=2 (since 2 and 3 together). So union 0 and 2, making all connected. Query (0,2) -> YES.
Matches.
Now check that the leaf 10 also might have edge from (3,7)? No, because 10 >7. So correct.
Now final output: YES, NO, YES.
Thus algorithm works.
Now let's also consider if there can be a query at time 1: For example, n=3, k=1, query at time1. Our intervals list empty. DSU initial. leaf1: no edges, query answer NO. That's correct.
Now we must ensure that if there is a query for u and v that are already connected by multiple edges, DSU will detect.
Now about the DSU rollback: When we union, we may connect components. The order of unions in a node matters? Not for connectivity, as long as all unions are applied.
Now one more nuance: In DSU unite, we use find to get roots. However, during the DFS, we apply unions in a node, then proceed to children. The DSU structure after applying unions is used for queries in the subtree. Since we roll back after subtree, it's fine.
Now consider the case where an edge is inserted and later deleted, and there are queries in between. That's fine.
Now we also need to consider that the input size is up to 40k, but there could be many edges and many intervals. The segment tree size is 4*40000 = 160k nodes. Each node's vector could be large if many intervals cover that node's range. In worst-case, if we have many intervals that are very long (e.g., all intervals are [1,k]), then each interval will be added only to the root node (since root covers whole range). So root node will have m edges, where m up to 40k. That's okay. If intervals are all short, they get distributed to many nodes. So total edges stored is O(m log k). So memory and time okay.
Now we might worry about recursion depth in add_interval when k=40000 and segment tree depth ~16; recursion fine.
Now consider the possibility of stack overflow due to recursion in dfs if we use function recursion for each node? Depth is about 16, so safe.
Now finalize code.
Potential improvements: Use iterative segment tree? Not needed.
Now produce final answer.
Edge Cases:
-
n=40000, k=40000, all operations are queries (type 3) with no edges. Then intervals list empty. DFS will go through all nodes, applying no edges, answering queries with NO. That's fine.
-
n=40000, k=40000, all operations are insertions of distinct edges (type1) from time1 to time20000, then queries from time20001 to 40000. Then intervals: each edge inserted at time i, never deleted, so interval [i+1, k]. So many intervals, each covering a suffix. Then segment tree will have each interval added to O(log k) nodes. So total edges stored ~ 20000*16=320k. Then DFS will process these. It's okay.
-
Mixed.
Now final code.
Now verify with sample.
We'll produce final solution.
Before finishing, ensure we don't have any undefined behavior: In DSU unite, we use find which returns int. We swap ra and rb if size[ra] < size[rb]. Then we attach rb under ra. But what if we swap and then later we push parent change for rb and size change for ra. That's fine.
Now about DSU rollback: We rely on hist having even number of entries for each union. But if union returns false, we push nothing. So rollback will still work.
Now about DSU find: Since we don't have path compression, but we also don't need to update anything. But note: In find, we access parent array which may be modified by rollbacks. That's fine.
Now about potential integer overflow: n up to 40000, size up to 40000, fine.
Now final answer code.
But we need to think about the memory overhead of segtree as vector of vectors. Each vector is initially empty; we allocate 4*N+5 vectors. That's 160k vectors; each vector has small overhead (typically 24 bytes), so about 3.8 MB. Acceptable.
However, some judges might have memory limit strict (like 256 MB) and 160k vectors may be okay. But we could reduce memory by building segment tree only over indices that are queries? Another approach is to compress time to only query times, but that's more complex. But given constraints, 160k vectors is fine.
But wait: 4N+5 for N=40000 gives 160005 vectors. Each vector has at least size of three pointers (e.g., 24 bytes on 64-bit). That's 160k24 ≈ 3.84 MB. Plus each stored edge is 8 bytes, plus overhead of vector capacity maybe some extra. So total maybe 10-15 MB. That's fine.
Now finalize.
One more check: In the code, we used function add_interval defined as lambda inside main, but it captures segtree and maybe others by reference. That's fine.
But we need to be careful: The lambda recursion calls itself; in C++, a lambda cannot be recursive unless we use std::function or declare it as a regular function. We used std::function in dfs but for add_interval we also used a recursive lambda via std::function? In the code above, we defined add_interval as a function object using std::function? In my skeleton I wrote:
function<void(int,int,int,int,int,int,int)> add_interval = [&](int node, int L, int R, int ql, int qr, int u, int v) {
...
};
But that's a std::function which may have overhead. Since add_interval is called many times (for each interval, O(log k) calls), it's better to implement add_interval as a regular function to avoid std::function overhead. But it's still okay given constraints. However, we can define a separate function (non-capturing) that takes segtree by reference, or we can use a recursive lambda with auto and std::function but it's fine.
But note: In C++, a lambda that captures cannot be used recursively easily without std::function because you need its type to call itself. But we can use a regular function. I'll just implement add_interval as a regular function outside main, taking parameters: segtree reference, node, L, R, ql, qr, u, v. Or we can keep std::function. It's okay.
Alternatively, we can avoid recursion in add_interval by iterative segment tree insertion? Not needed.
Given that k is only 40k, the overhead of std::function is negligible.
But to be safe and efficient, I'll implement add_interval as a separate function that takes the segtree vector by reference, or as a lambda that captures by reference and then assign to auto variable using y-combinator trick, but simpler: write a regular function.
I'll restructure: define a function add_interval that takes parameters: vector<vector<pair<int,int>>> &segtree, int node, int L, int R, int ql, int qr, int u, int v. Then call it in loop.
But then we need to pass segtree each time. That's fine.
But to avoid passing segtree each time, we can define it inside main as a lambda that captures segtree by reference, and then we can use function recursion by storing it in a std::function. It's okay.
Given typical CP, using std::function for log depth recursion is fine for 40k intervals.
Alternatively, we can implement segment tree insertion iteratively: For each interval [l,r], we can convert to node ranges using standard method (like add to nodes in a loop). But recursion is simpler.
I'll stick with recursion using std::function.
Now about DSU: We used struct with public members; fine.
Now final code.
But I want to be absolutely sure about the mapping of active intervals. Let's test another scenario: Insert at time i, query at time i+1, delete at time i+2. According to our mapping, edge active for queries at i+1. Works.
What about multiple insertions and deletions of the same edge with queries between? Works.
Now consider a scenario where an edge is inserted at time i, then later inserted again without being deleted? Not allowed.
Now consider scenario where an edge is deleted at time i but never inserted? Not allowed.
Now consider scenario where u and v are same? Input says u < v, so distinct.
Now think about connectivity when there are multiple components.
Now we are good.
Now also check for potential bug: In DSU, we might want to store size as int and ensure no overflow.
Now about using map for start: If we use unordered_map, we need a hash function for pair. Simpler to use map.
Now final code produce.
But there is one more nuance: In the sample, we had query at time 6: (0,1). At that time, edge (0,1) not present, but there is edge (0,2) and (2,3). So not connected. DSU should show separate components. Works.
Now think about the order of applying edges at a node: For leaf 6, before reaching leaf 6, we apply edges from ancestor nodes that cover range containing 6. In segment tree, the edges are placed in nodes that fully cover subranges. For interval (3,7) it might be placed in node covering [3,4] or [3,7] depending on implementation. But wherever it is placed, it will be applied at some node on the path to leaf 6. That's fine.
Now check the correctness of add_interval: It adds edge to node if node interval is completely inside [ql,qr]. That's standard. So if we have interval [3,7] and node covering [1,5] is not fully inside, so we go down to children; eventually it will be added to nodes like [3,4] and [5,5] etc. So edges will be applied to nodes that cover subranges fully inside interval.
Now DFS: At each node, we apply all edges stored there. So for leaf 6, the path from root to leaf includes nodes like root [1,10], then maybe [6,10], then [6,8], then [6,6] etc. The edges that cover 6 will be stored in some of these nodes if those nodes are fully inside the interval. So they will be applied at the appropriate level.
Thus the set of edges applied at leaf 6 will be the union of all edges from nodes on path that are fully inside interval. That exactly corresponds to edges active at time 6.
So correct.
Now final code.
Potential improvements: For segment tree, we used 1-indexed node indexing: root=1, children 2i, 2i+1. That's fine.
Now we need to be careful about recursion depth when N=40000, the segment tree depth is about ceil(log2(40000)) = 16, so recursion depth of add_interval is up to 16, fine.
Now time complexity: O((m log k + k) * log n). With m up to 40k, k up to 40k, log n ~ 16, total operations maybe few million, fine.
Now final answer.
Now produce the final code.
We'll also add comments for clarity.
One more check: In DSU, when we rollback, we pop from hist. But hist contains changes for both parent and size. In the case of no union (already connected), we push nothing. So rollback works.
Now about DSU find: Since we don't have path compression, find may be called many times. In DFS, for each query we call find twice. That's fine.
Now we could also use iterative find.
Now implement.
Now let's write the code.
Potential bug: In DSU, getSize returns hist.size() which is size_t; we store in int snap. That's okay as long as hist.size() fits in int, which it does (max 1.28M). Fine.
Now code.
--- final code ---
I'll produce final answer with code. ```cpp
#include <bits/stdc++.h>
using namespace std;
// ---------- Disjoint Set Union with rollback ----------
struct DSU {
vector parent, sz;
struct Change {
int type; // 0: parent change, 1: size change
int node;
int old_val;
};
vector hist;
DSU(int n) : parent(n), sz(n, 1) {
for (int i = 0; i < n; ++i) parent[i] = i;
}
// find without path compression
int find(int x) const {
while (parent[x] != x) x = parent[x];
return x;
}
// union by size, return true if merged
bool unite(int a, int b) {
int ra = find(a);
int rb = find(b);
if (ra == rb) return false;
if (sz[ra] < sz[rb]) swap(ra, rb);
// attach rb under ra
hist.push_back({0, rb, parent[rb]});
parent[rb] = ra;
hist.push_back({1, ra, sz[ra]});
sz[ra] += sz[rb];
return true;
}
int getSize() const {
return hist.size();
}
void rollback(int target) {
while (hist.size() > target) {
Change ch = hist.back();
hist.pop_back();
if (ch.type == 0) parent[ch.node] = ch.old_val;
else sz[ch.node] = ch.old_val;
}
}
};
// -------------------------------------------------------
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, k;
cin >> n >> k;
// ----- read operations, record intervals and queries -----
vector<int> opType(k + 1);
vector<pair<int, int>> opUV(k + 1);
vector<int> query_u(k + 1), query_v(k + 1), query_id(k + 1, -1);
int qcnt = 0;
map<pair<int, int>, int> start; // (u,v) -> insertion time
vector<tuple<int, int, int, int>> intervals; // (l, r, u, v)
for (int i = 1; i <= k; ++i) {
int t, u, v;
cin >> t >> u >> v;
opType[i] = t;
opUV[i] = {u, v};
if (t == 1) {
start[{u, v}] = i;
} else if (t == 2) {
auto it = start.find({u, v});
// guaranteed to exist
int l = it->second + 1;
int r = i - 1;
if (l <= r) {
intervals.emplace_back(l, r, u, v);
}
start.erase(it);
} else { // t == 3
query_u[i] = u;
query_v[i] = v;
query_id[i] = qcnt++;
}
}
// edges still alive at the end
for (auto &[edge, s] : start) {
int l = s + 1;
int r = k;
if (l <= r) {
intervals.emplace_back(l, r, edge.first, edge.second);
}
}
// ----- build segment tree over time indices [1, k] -----
int N = k;
vector<vector<pair<int, int>>> segtree(4 * N + 5);
function<void(int, int, int, int, int, int, int)> addInterval =
[&](int node, int L, int R, int ql, int qr, int u, int v) {
if (ql > R || qr < L) return;
if (ql <= L && R <= qr) {
segtree[node].emplace_back(u, v);
return;
}
int mid = (L + R) / 2;
addInterval(node * 2, L, mid, ql, qr, u, v);
addInterval(node * 2 + 1, mid + 1, R, ql, qr, u, v);
};
for (auto &[l, r, u, v] : intervals) {
addInterval(1, 1, N, l, r, u, v);
}
// ----- traverse the segment tree and answer queries -----
DSU dsu(n);
vector<string> answers(qcnt);
function<void(int, int, int)> dfs = [&](int node, int L, int R) {
int snap = dsu.getSize();
// apply all edges stored in this node
for (auto &[u, v] : segtree[node]) {
dsu.unite(u, v);
}
if (L == R) {
// leaf corresponds to time L
int id = query_id[L];
if (id != -1) {
bool conn = (dsu.find(query_u[L]) == dsu.find(query_v[L]));
answers[id] = conn ? "YES" : "NO";
}
} else {
int mid = (L + R) / 2;
dfs(node * 2, L, mid);
dfs(node * 2 + 1, mid + 1, R);
}
// undo changes made in this node
dsu.rollback(snap);
};
dfs(1, 1, N);
// ----- output -----
for (auto &ans : answers) {
cout << ans << '\n';
}
return 0;
}