Andrew plays a game called "Civilization". Dima helps him.
The game has n cities and m bidirectional roads. The cities are numbered from 1 to n. Between any pair of cities there either is a single (unique) path, or there is no path at all. A path is such a sequence of distinct cities v1, v2, ..., vk, that there is a road between any contiguous cities vi and vi + 1 (1 ≤ i < k). The length of the described path equals to (k - 1). We assume that two cities lie in the same region if and only if, there is a path connecting these two cities.
During the game events of two types take place:
Andrew asks Dima about the length of the longest path in the region where city x lies.
Andrew asks Dima to merge the region where city x lies with the region where city y lies. If the cities lie in the same region, then no merging is needed. Otherwise, you need to merge the regions as follows: choose a city from the first region, a city from the second region and connect them by a road so as to minimize the length of the longest path in the resulting region. If there are multiple ways to do so, you are allowed to choose any of them.
Dima finds it hard to execute Andrew's queries, so he asks you to help him. Help Dima.
Input
The first line contains three integers n, m, q (1 ≤ n ≤ 3·105; 0 ≤ m < n; 1 ≤ q ≤ 3·105) — the number of cities, the number of the roads we already have and the number of queries, correspondingly.
Each of the following m lines contains two integers, ai and bi (ai ≠ bi; 1 ≤ ai, bi ≤ n). These numbers represent the road between cities ai and bi. There can be at most one road between two cities.
Each of the following q lines contains one of the two events in the following format:
1 xi. It is the request Andrew gives to Dima to find the length of the maximum path in the region that contains city xi (1 ≤ xi ≤ n).
2 xi yi. It is the request Andrew gives to Dima to merge the region that contains city xi and the region that contains city yi (1 ≤ xi, yi ≤ n). Note, that xi can be equal to yi.
Output
For each event of the first type print the answer on a separate line.
Examples
Input
6 0 6
2 1 2
2 3 4
2 5 6
2 3 2
2 5 3
1 1
Output
4
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to handle dynamic forest (initially a forest with n nodes and m edges, m < n, so it's a forest possibly with multiple components). Queries: type 1: ask for the diameter (longest path length) of the component containing node x. type 2: merge two components of nodes x and y. If already same, nothing. Otherwise we need to connect two trees with a single edge in such a way that the new diameter (the longest path in the merged tree) is minimized. We can choose any pair of nodes from the two components to connect. The goal is to minimize the new diameter, and we are allowed to pick the optimal connection. We need to output answers for type1 queries.
We need a data structure that can support union of trees with optimal connection and query for diameter.
Observation: When merging two trees T1 and T2, we can choose two nodes u in T1, v in T2 to add an edge. The resulting tree's diameter will be at least max(diameter(T1), diameter(T2)). But by connecting wisely, we can try to keep it as small as possible. The diameter after connecting will be max( diam1, diam2, ceil(d1/2) + ceil(d2/2) + 1 ), where d1 = diameter(T1), d2 = diameter(T2), and ceil(d1/2) is the radius (the smallest integer r such that the tree can be covered by a node at distance <= r). Actually the longest possible distance between two nodes in the merged tree can be: maybe a path that goes from some node a in T1 to some node b in T2 via new edge. The longest such path is the distance from the farthest node in T1 from u plus distance from u to v (1) plus distance from v to farthest node in T2. To minimize the maximum over all pairs, we would choose u and v to be centers (or nodes that minimize the maximum distance to other nodes in their tree). The best we can do is to connect the centers (or nodes near centers) to minimize the new longest path that crosses between trees. The new diameter = max( d1, d2, radius(T1) + radius(T2) + 1 ). However, we need to be careful: The radius is typically defined as half the diameter (rounded up). Actually for a tree, the minimal value r such that there exists a node whose farthest distance is r is the radius. And the radius = ceil(diameter/2). Moreover, the set of centers are nodes with eccentricity equal to the radius. When connecting two centers, the distance from the farthest node in T1 to the farthest node in T2 via those centers is at most radius(T1) + 1 + radius(T2). However, could it be smaller if we connect not exactly centers but other nodes? The worst-case path that goes through the new edge will be (max distance from u in T1) + 1 + (max distance from v in T2). We want to minimize the maximum of: d1, d2, and that sum. Since d1 and d2 are fixed, we want to minimize max(d1, d2, min_{u in T1, v in T2} (ecc_T1(u) + 1 + ecc_T2(v))). The minimum possible sum ecc_T1(u)+ecc_T2(v) is radius(T1)+radius(T2) because the minimum possible eccentricity in a tree is the radius. And we can achieve this by picking u as a center of T1 and v as a center of T2. So indeed the optimal new diameter is max( d1, d2, radius(T1) + radius(T2) + 1 ). And since radius = ceil(d/2), we have radius1 + radius2 + 1 = ceil(d1/2) + ceil(d2/2) + 1.
Thus the merged tree's diameter can be computed as: new_d = max(d1, d2, (d1+1)//2 + (d2+1)//2 + 1). Actually careful: ceil(d/2) = (d+1)//2 integer division. So formula: new_d = max(d1, d2, (d1+1)//2 + (d2+1)//2 + 1).
But is that always minimal? Consider if the diameters of the trees are large and we connect centers, the longest cross path could be less than both diameters? Actually if d1 > d2, then new_d might be d1 if d1 >= (rad1+rad2+1). But sometimes d1 might be less than that sum, then new_d becomes that sum. So correct.
Thus we need to maintain for each component: its diameter. Also to compute merged diameter we only need diameters of both components. So we can maintain using DSU with extra information: for each root, store the diameter of that component. When merging two components, compute new diameter as above, and set for the new root that value. Also we need to support type1 queries: given node x, find its root and output the stored diameter.
The only catch: The initial forest might have edges given, and we need to compute the diameter for each initial component. Then we process queries: type2 merges two components, but we also actually add an edge between the two trees? However, the query says: "Andrew asks Dima to merge the region where city x lies with the region where city y lies. If the cities lie in the same region, then no merging is needed. Otherwise, you need to merge the regions as follows: choose a city from the first region, a city from the second region and connect them by a road so as to minimize the length of the longest path in the resulting region. If there are multiple ways to do so, you are allowed to choose any of them." So we must connect them with an edge. But does that edge remain for future merges? Yes, after merging, the region becomes a single tree (connected component). So subsequent queries will see that merged tree.
But we are not required to actually construct the new tree's structure beyond maintaining diameters. However, when we later merge this component with another, we will need its diameter. So as long as we can compute the new diameter using the formula, we don't need to know the actual structure. But wait: is the formula correct regardless of which nodes we connected? Because the new tree's diameter depends on how we connected, and we are choosing optimally. So we can always achieve that minimal diameter. But after merging, the resulting tree's structure matters for future merges: its diameter is whatever we compute (the minimal possible). But is there any subtlety that after merging, the "radius" of the new tree is not simply derived from the diameter? Actually, when we need to merge this new tree with another later, we will again need its diameter (and we might also need its radius). However, to compute future merges, we only need the diameter of each component, not the radius? Because the formula for merging two trees uses only their diameters (since radius = ceil(d/2)). That is correct: given a tree with diameter d, the minimal eccentricity (radius) = ceil(d/2). However, is it always true that if we merge two trees optimally, the resulting tree's radius is exactly ceil(new_d/2)? That's a property of any tree: radius = ceil(diameter/2). So we don't need to store radius separately; we can compute it from the diameter when merging. Therefore, we just need to store diameter per component.
But wait: Is there any scenario where after merging optimally, the new tree's diameter is not simply given by the formula because the optimal connection might affect the diameter in a more complex way? Let's double-check. Suppose we have two trees T1 and T2 with diameters d1 and d2, and radii r1=ceil(d1/2), r2=ceil(d2/2). We can connect a center c1 in T1 and a center c2 in T2. Then any longest path in the merged tree either lies entirely within T1 (d1), within T2 (d2), or crosses the new edge. The longest cross path is at most r1+1+r2. But is it exactly r1+1+r2? Could be less if the farthest node in T1 from c1 is at distance < r1? Actually by definition of center, eccentricity of c1 = r1, so there is at least one node at distance r1 from c1. So maximum distance from c1 in T1 is exactly r1. Similarly for c2. So there exists a node a in T1 at distance r1 from c1, and a node b in T2 at distance r2 from c2. Then the path a-c1-c2-b has length r1+1+r2. So that is achievable. So cross path length = r1+1+r2. So the diameter is at least that. Could there be a path that is longer than max(d1, d2, r1+r2+1)? Possibly if some other pair yields longer distance? For any node u in T1 and v in T2, distance = dist_T1(u, c1) + 1 + dist_T2(v, c2) if we take the unique path via c1 and c2? Actually the path from u to v goes from u to c1 (since c1 is somewhere on the path?), Not necessarily. In a tree, the path from u in T1 to v in T2 goes: u -> ... -> the connection point (the new edge between the two trees). If we connect c1 and c2, then the unique path goes from u to c1 (along tree T1), then edge c1-c2, then c2 to v. So distance = dist_T1(u, c1) + 1 + dist_T2(v, c2). So the maximum over u,v is max_u dist_T1(u, c1) + 1 + max_v dist_T2(v, c2) = r1+1+r2. So cross path max is exactly that. So the diameter is max(d1, d2, r1+1+r2). Since we can choose which nodes to connect, we can minimize this max by choosing centers. And we cannot do better because the cross path must involve some node from each tree, and for any chosen connection nodes u and v, the max cross path will be ecc_T1(u)+1+ecc_T2(v). The minimum possible over u and v is r1+1+r2 (since min ecc_T1(u)=r1, min ecc_T2(v)=r2). So indeed the minimal achievable diameter = max(d1, d2, r1+r2+1). So formula holds.
Therefore we can just use DSU storing diameter.
But we need to compute initial diameters for each component given the initial forest (with m edges). n up to 3e5, m < n, but there could be many components initially. So we need to compute the diameter for each component. Since we have a forest, we can perform DFS/BFS from each node to compute the farthest node, then from that farthest node compute distances to get diameter for each component. But we need to handle up to 3e5 nodes, and we have to process q queries online. But initial diameters can be computed offline before processing queries. That's fine: O(n) time.
After that, we process queries: type1: output diameter[find(x)]. type2: union(x,y) with diameter update using formula. Also note that type2 queries might be merging components that are already same: then do nothing.
We also need to consider that the new edge added to connect the components is not actually stored in our data structure. But we don't need to store the tree structure beyond DSU. Because future merges only need diameters. However, what about if later we need to compute something else? No, only diameter. So we don't need to keep track of the actual tree.
Thus the problem reduces to: given initial forest, compute diameter for each component. Then support DSU unions with diameter update rule.
Edge Cases: The initial forest may have zero edges, so each node is a separate component with diameter 0 (single node). Merging two single nodes: d1=0,d2=0 => new_d = max(0,0, (0+1)//2 + (0+1)//2 + 1) = (0? Let's compute: (0+1)//2 = 0? Actually (0+1)//2 = 0 because integer division: 1//2 = 0. So r=0. So sum = 0+0+1=1. So new_d=1. That's correct: connect two nodes with edge => the path length is 1 (two nodes). So diameter=1.
Another: Single node (d=0) merged with tree with diameter d2. new_d = max(0, d2, (0+1)//2=0 + (d2+1)//2 + 1). So max(d2, ceil(d2/2)+1). Compare: For d2=1, ceil(1/2)=1? Actually (1+1)//2=1, so sum=0+1+1=2, max(1,2)=2. But is that correct? Merge a single node to a tree of two nodes (a line of length 1, diameter=1). If we connect the single node to an endpoint, the new tree is a path of length 2 => diameter=2. If we connect to the middle? There is no middle; the tree of two nodes has only two nodes. Connect to either node yields a path of three nodes line => diameter=2. So correct.
For d2=2 (path of length 2, nodes A-B-C). Ceil(2/2)=1? Actually (2+1)//2=1? Wait (2+1)//2=3//2=1. So sum=0+1+1=2. max(2,2)=2. So new_d=2. Is that optimal? If we connect the single node to the middle node B, then diameter remains 2 (path A-B-D? Actually D new node, connect to B: distances: A to C is 2, A to D is 2 (A-B-D), C to D is 2 (C-B-D). So diameter=2). So optimal is 2. Good.
Now consider merging two trees with diameters 2 and 2. Ceil(2/2)=1 each, sum=1+1+1=3, max(2,2,3)=3. So new diameter=3. Example: two paths of 3 nodes each (length 2). If we connect centers appropriately, we might get diameter 3. Let's test: path A-B-C and D-E-F. Centers: B and E. Connect B-E: distances: A to F: A-B-E-F = 1+1+1=3, A to D: A-B-E-D = 1+1+1=3, C to D: C-B-E-D = 1+1+1=3, C to F: C-B-E-F = 1+1+1=3. So diameter=3. Could we get 2? Not possible because each component has diameter 2, merging introduces at least one extra edge. So yes.
Thus formula works.
Now we just need to implement DSU with diameter. But careful: The DSU union must also update root; we compute new diameter and store it in the new root.
However, there is a nuance: When merging, we are free to choose the connection nodes arbitrarily. The formula yields the minimal possible diameter. But does the actual structure after merging affect future merges? In principle, if we always achieve that minimal diameter, then the component's diameter is exactly the computed value. But is it always possible to achieve that diameter in a way that also yields the same radius relationship? Yes, as we argued, we can connect centers. The resulting tree's diameter is exactly new_d as computed. Therefore, for future merges, we can treat the component as having that diameter. However, one might worry: after merging by connecting centers, the new tree's diameter is new_d, but its radius (ceil(new_d/2)) is indeed the value used for future merges. That radius may be different from the sum of previous radii etc. But it's fine.
Thus the solution is straightforward.
But wait: There is also possibility that there are type 2 queries merging the same component? Already handled.
Now we need to compute initial diameters. Since the graph is a forest (acyclic and may be disconnected). For each component, we can run BFS/DFS twice to compute diameter. Complexity O(n). But we must be careful about recursion depth (n up to 3e5). Use iterative BFS or stack.
Implementation plan:
Input n, m, q.
Build adjacency list for the initial forest (since m < n, it's forest; but is it guaranteed that there are no cycles? The problem statement says: "Between any pair of cities there either is a single (unique) path, or there is no path at all." That indicates the graph is a forest (acyclic). And they also say "0 ≤ m < n", so it's indeed a forest because for a tree we need exactly n-1 edges for connectivity, but here m < n, and it's acyclic by statement (unique path or none). So it's a forest (collection of trees). Good.
Then we need to compute for each node the component root (maybe via DSU initially). But for diameter computation, we could also use DSU to track connectivity, but we need to compute diameters for each component. Simpler: Use a visited array, for each unvisited node, run BFS/DFS to find farthest node. However, we also need to assign each node to a DSU set for queries. So we can initialize DSU with n nodes, but initially we haven't added any edges? Actually the initial graph has m edges, which we need to reflect in DSU. So we can create DSU and for each given edge (a,b), we union them (without diameter update? We need to union them but also compute diameters after all unions? Actually we can compute diameters after building the graph using BFS, then set the diameter for each DSU root. However, if we union edges during input, the DSU structure will track connectivity, but the diameter information is not yet known. We can first read edges, build adjacency list, and also union them in DSU to have connectivity sets. After reading all initial edges, we compute diameters per component: For each component root (find representative), we need to compute the diameter. But careful: When we compute diameter using BFS, we need to know which nodes belong to each component. We can use DSU to get components: we can iterate over nodes, for each node, find its root, and store nodes per root. But that would be O(n α(n)) but we also need to map root to a list. That is okay O(n). Then for each root, we run two BFS from any node (e.g., the first node in the list) to get farthest node, then from that farthest node to get distances, and the max distance is the diameter. But BFS per component total visits each node once overall, so total O(n). However, we need to avoid O(n) per component for storing lists? We can simply run a global DFS that marks component IDs. Since the graph is a forest, we can do a loop: for each node not visited, run BFS to find farthest and compute diameter, and also assign component ID. But we also need to assign each node to a DSU set: we have already performed unions for edges, so each node's DSU root is the representative of its component. But note that DSU union path compression may have changed some roots, but we can still retrieve the component representative using find. However, when we run BFS, we can also determine the set of nodes in that component. But we need to ensure we don't compute diameter multiple times per component. Simpler: Use DSU only for queries, and compute initial diameters by performing two BFS on each component without using DSU. Then after computing diameter for a component, we need to set the diameter for each node's DSU root. But DSU might have representatives that are not consistent with component IDs we found via BFS. We can, after BFS, for each node visited, we find its DSU root (by calling find) and set the diameter for that root. However, multiple nodes in the same component will have the same DSU root because we performed unions. So we can after BFS, pick any node, find its root, and set diameter[root] = computed_d. That's fine.
But there is a nuance: DSU might not have path compression fully yet; but we can call find to get representative. Since we performed unions for all initial edges, the DSU structure correctly partitions nodes. So we can compute diameters independently.
Alternatively, we can first compute diameters using two BFS on the forest and then fill DSU with the diameters. That's simpler: Initialize DSU with each node separate (no unions initially). But we need to incorporate initial edges. However, for diameter computation we need connectivity. So we must have the edges built in the graph. We can build adjacency list and also do DSU union to keep track of connectivity for queries. So we do both: while reading m edges, add to adjacency list and union in DSU. Then after reading all edges, we compute diameters for each DSU component. To avoid confusion, we can compute diameters by iterating over nodes, find their DSU root, and for each root we want to compute diameter. But we need to actually perform BFS on the component's nodes. We can do:
visited array initially false.
For each node i from 1..n:
if not visited[i]:
// do BFS/DFS to get all nodes in this component and compute diameter.
// but we also need to know DSU root? Actually we don't need DSU for that; BFS using adjacency list will traverse the component.
// Since the graph is a forest (connected component is a tree), BFS will work.
// So we compute diameter for the component without using DSU.
// Then we need to set the diameter for the DSU root of this component. But we can, after BFS, take the first node (i) and find its DSU root (since all nodes in the component have same DSU root because we performed unions). So set dia[find(i)] = computed_d.
// Mark all nodes visited.
But careful: DSU might have multiple representatives within the same component if we haven't fully unioned? No, we did union for each edge, so all nodes in a tree are connected via unions, thus they belong to the same DSU set. However, due to path compression not done for all, find(i) might return some representative; but all nodes will have the same representative root after path compression if we call find on each? Not necessarily: without extra path compression, find(i) may return different "representative" values but they should all be in the same set (i.e., find(i) == find(j) should be true). However, if we call find(i) on one node, we get some root. But if we call find(j) on another node, it might return a different root if they are not compressed to the same root? Actually DSU ensures that if two nodes are connected, find will eventually return the same root because of union-by-rank and path compression. But before any find calls, the parent pointers might not be fully compressed. However, if we call find(i) for node i, it will compress its path to the root, but find(j) might still return a different root if the set's representation hasn't been unified? Let's think: DSU union operation sets parent of one root to another. So after all unions, each set has a unique root. For any node, find will traverse parent pointers up to the root. For nodes in the same set, they will eventually reach the same root because the union operations create a tree that converges to the root. So find(i) and find(j) should return the same root regardless of path compression. However, if we haven't called find on some nodes, their parent may point to some intermediate node but still eventually leads to the root. So find(i) will give the root. So it's fine.
Thus algorithm:
Initialize DSU with n elements, parent[i]=i, rank/size array.
adjacency list: vector<vector> g(n+1).
For each of m edges (a,b):
g[a].push_back(b); g[b].push_back(a);
unionSets(a,b) in DSU (but only for DSU, not for diameter).
After reading all edges and unions, we need to compute diameter for each component. We'll have an array dia of size n+1 for DSU roots, initially 0 (or maybe compute later). We'll also have an array visited (bool) of size n+1, false.
For i=1..n:
if not visited[i]:
// component nodes list? But we just need diameter.
// Use BFS/DFS to compute diameter.
// Since the component is a tree (or a single node), we can compute diameter by two BFS.
// First BFS from i to find farthest node u.
// Second BFS from u to get max distance d (diameter length in edges count? The problem defines length of path as k-1 (number of edges). So diameter is the maximum number of edges in any shortest path. So BFS distances in edges count.)
// However, the component might be disconnected? Actually i is part of one component, BFS will traverse entire component.
// After second BFS, we have the max distance as diameter.
// Then we need to set dia for the DSU root. Get root = find(i) (or any node from component, say i). Set dia[root] = d.
// Mark all nodes visited during BFS as visited.
But careful: The BFS from i to find farthest node u: we need to run BFS on the entire component. That's fine: BFS will mark visited. However, we also need to mark visited during first BFS. But we want to avoid visiting nodes multiple times for different components. So we can do:
for i in 1..n:
if not visited[i]:
// Perform first BFS from i to find farthest node u and also mark visited for all nodes discovered.
// But then second BFS from u should also be within same component. The visited marks from first BFS already mark all nodes visited, but then second BFS would not traverse because visited is already true. So we need to either:
- Use separate visitation for BFS steps but still need to know component nodes.
We can do a two-pass BFS without marking visited globally for first pass? Actually we need to compute farthest node from i. But we also want to avoid re-traversing nodes from other components. The simplest: For each component, we can collect all nodes (by BFS/DFS) first, store them in a list, and then run two BFSs on that component using a temporary distance array, but careful that visited marks across components.
One approach: Use a queue and a visited array for the whole graph. But for two BFSs, we need to reset visited for the second BFS within the same component. We can do:
From start node i, perform BFS to find farthest node u, while also marking visited[i] = true for all nodes in the component? Actually we can mark visited globally only after we are done with the component. But during the first BFS, we might need to traverse the component; we can use a temporary "comp" list to store nodes visited. So algorithm:
For i=1..n:
if not visited[i]:
// first BFS from i
queue, dist array (or we can use distance map, but we can use an array of size n+1, but we would need to reset after each component; that could be O(n^2) if we clear all. Better to use a distance array that we reinitialize only for nodes in component. So:
vector comp; // nodes in component
queue q;
q.push(i);
dist[i] = 0; // we can use a global dist array, but set for nodes in component, then later clear.
visitedComp[i] = true; // but we have visited array to avoid re-entering other components. We'll use a separate "seen" array for this BFS? Actually we can reuse visited array but we need to distinguish that we haven't marked these nodes as visited globally until we finish the component. We can have a global visited array for final marking after processing component. But during BFS, we may mark nodes as visited to avoid adding them again within the same BFS; but if we mark visited globally, they will not be considered later in the outer loop. That's fine; we want to process each component exactly once. So we can mark visited when we first see a node. So:
code
visited[i] = true;
q.push(i);
comp.push_back(i);
while q not empty:
v = q.pop();
for neighbor in g[v]:
if not visited[neighbor]:
visited[neighbor]=true;
comp.push_back(neighbor);
q.push(neighbor);
// After this, we have all nodes of component in comp, and visited is set for them.
// But we also need distances for first BFS to find farthest node from i. Actually we didn't record distances. So we need a BFS that computes distances. So we can combine: while exploring we can compute distances using a distance array (maybe a map or separate array). We can do first BFS to compute distances from i, but we also mark visited globally at the same time? That's okay: we do BFS from i, marking visited as we go, compute distances, and track farthest node. But after that BFS, all nodes in component are visited (global). Then we need to do second BFS from the farthest node u. But visited is already true for all nodes, so we cannot re-traverse them unless we use a different mechanism. So we need to be able to run BFS again on the same component. We can use a temporary "timestamp" technique: use an array "mark" with integer timestamp, or we can clear visited for those nodes after we are done? But visited is used to avoid processing component again; we can't clear visited. So we need separate "seen" for the BFS within component.
Option 1: Do two BFS without marking global visited. Instead, after we identify component, we mark global visited but then for BFS we ignore global visited and use a local distance array and maybe a queue that we refill from component list. But we need to avoid re-traversing nodes from other components; but since we know the component nodes, we can restrict BFS to those nodes. We could use a map or set of component nodes to quickly check if neighbor belongs to component. But that would be expensive.
Better approach: For each component, we can run two BFS using a queue and a distance array, and use a separate array "vis" that we reset for each component by clearing after use. Since total nodes across all components is n, we can just use a global array "dist" and a global array "seen" with timestamp. For each component, we increment a timestamp, and when we visit a node we set seen[node] = timestamp. This avoids clearing arrays. This is efficient.
Thus:
Initialize global arrays dist[1..n] (int) and seen[1..n] (int) initially 0.
timestamp = 0.
For i=1..n:
if seen[i] == 0: // not visited in any component yet
// We'll process this component.
code
// First BFS to find farthest node u.
timestamp++;
queue<int> q;
q.push(i);
seen[i] = timestamp;
dist[i] = 0;
int u = i;
while (!q.empty()) {
int v = q.front(); q.pop();
for (int to : g[v]) {
if (seen[to] != timestamp) {
seen[to] = timestamp;
dist[to] = dist[v] + 1;
q.push(to);
if (dist[to] > dist[u]) u = to;
}
}
}
// Second BFS from u to compute diameter.
timestamp++;
q = queue<int>();
q.push(u);
seen[u] = timestamp;
dist[u] = 0;
int maxDist = 0;
while (!q.empty()) {
int v = q.front(); q.pop();
for (int to : g[v]) {
if (seen[to] != timestamp) {
seen[to] = timestamp;
dist[to] = dist[v] + 1;
q.push(to);
if (dist[to] > maxDist) maxDist = dist[to];
}
}
}
// maxDist is the diameter (in edges).
// Now we need to assign this diameter to the DSU root of this component.
int root = find(i); // any node, i is in component, DSU find returns root.
dia[root] = maxDist;
// Note: We used seen to mark nodes during BFS, but we haven't globally marked nodes as processed for outer loop? We need to ensure that the outer loop doesn't process nodes from this component again. We used seen to mark visited during BFS, but after we finish, seen values are the last timestamp used in second BFS. The next iteration of outer loop might see a node with seen != 0? Actually after processing component, all nodes have seen set to some timestamp (the last one from second BFS). Since we use the condition if (seen[i]==0) to start a new component, and after second BFS, seen[i] is not 0. So they will be skipped. However, note that timestamp increments each time we start a component, and we use two timestamps per component (first BFS and second BFS). After second BFS, all nodes in the component have seen = timestamp (the second BFS timestamp). The next component will have a larger timestamp, so those nodes will have seen < new timestamp but not zero. Our check is if seen[i]==0, which will be false for those nodes. So they won't be reprocessed. That's fine. But what about nodes that were visited only in first BFS but not second? Actually in second BFS we mark all nodes again. So both BFS cover the entire component. So all nodes get seen set to the second timestamp. Good.
Thus we compute initial diameters.
Now DSU: We need to maintain parent, rank/size, and diameter value per root. For union, we combine two sets, compute new diameter as max(dia[rootX], dia[rootY], (dia[rootX]+1)/2 + (dia[rootY]+1)/2 + 1). Then set the new root's diameter to this value. We also need to update parent pointers.
Implementation details:
DSU arrays: parent[n+1], rank[n+1] or size[n+1], dia[n+1] (diameter for the root). Initially, before computing diameters, we set dia for each node? But we will compute after union edges and set dia for root. For nodes that are isolated (single nodes), they will be processed as components: diameter 0. So dia[root] will be set accordingly.
For DSU find with path compression.
For union, we do:
void unite(int a, int b) {
a = find(a); b = find(b);
if (a == b) return;
// merge by rank/size
if (rank[a] < rank[b]) swap(a,b);
parent[b] = a;
if (rank[a] == rank[b]) rank[a]++;
// compute new diameter
int new_dia = max({dia[a], dia[b], (dia[a]+1)/2 + (dia[b]+1)/2 + 1});
dia[a] = new_dia;
// Note: we need to also maybe update size if we use size for something else; but we only need rank for union.
}
But careful: When we swap, we must also ensure that the new root's diameter is stored in the root we keep (a). But after swapping a and b, a is the root with larger rank, and we attach b under a. The diameter we compute should be based on the original diameters of the two components. So we compute before possibly swapping? Actually we should compute using the values of dia[a] and dia[b] after we have identified roots but before swapping. However if we swap for union by rank, the new root after union might be a or b. We can decide which root to keep as root (say we always attach smaller rank to larger rank). Then after deciding final root (say rootX) and child rootY, we set dia[rootX] = new_dia. So we can compute new_dia using the diameters of the two roots before merging. So:
int ra = find(a), rb = find(b);
if (ra == rb) return;
if (rank[ra] < rank[rb]) swap(ra, rb);
parent[rb] = ra;
if (rank[ra] == rank[rb]) rank[ra]++;
int new_d = max({dia[ra], dia[rb], (dia[ra]+1)/2 + (dia[rb]+1)/2 + 1});
dia[ra] = new_d;
But note: if we swapped ra and rb, then dia[ra] and dia[rb] refer to the diameters of the sets after swap? Actually we swapped ra and rb, so after swap, ra is the larger rank (or originally the one we keep as root), and rb is the smaller. However dia[ra] and dia[rb] correspond to the diameters of the sets they represent, which haven't changed. That's fine because we still have correct values.
But we must ensure that after swap, ra is the root we are keeping; we assign parent[rb] = ra. Then we set dia[ra] = new_d.
Now for queries:
For type 1 x: find root = find(x); output dia[root].
For type 2 x y: call unite(x,y).
But wait: there is nuance: The query type 2 says: "merge the region where city x lies with the region where city y lies. ... If the cities lie in the same region, then no merging is needed. Otherwise, you need to merge the regions as follows: choose a city from the first region, a city from the second region and connect them by a road so as to minimize the length of the longest path in the resulting region. If there are multiple ways to do so, you are allowed to choose any of them." So we are to merge the components. The formula we derived gives the minimal possible diameter after merging. So we should compute new diameter accordingly. However, is it always optimal to connect centers? Yes. So the resulting diameter is as given. So we can just update diameter accordingly.
But we need to confirm that when we merge components that have been merged before using this formula, the resulting component's diameter is exactly the computed new_d. And for future merges, we can again use the same formula based solely on diameters. This is correct because the formula depends only on the diameters of the two trees, not on their internal structure. And the optimal connection yields exactly that diameter.
One more nuance: When we merge two trees, we add an edge. The new tree's diameter is either one of the original diameters or rad1+rad2+1. However, is it always exactly that value? Could there be a scenario where after connecting centers, the actual diameter is less than rad1+rad2+1? No, because we argued that there exist nodes at distances rad1 and rad2 from the centers, so the cross path length is exactly rad1+rad2+1. So diameter is at least that. It might be exactly that if that sum is >= d1 and d2. If it is less than d1 or d2, then diameter = max(d1, d2). So the new diameter computed as max(d1, d2, rad1+rad2+1) is accurate.
Thus DSU approach works.
Now complexity: O((n+m+q) α(n)), which is fine.
Edge Cases:
n up to 300k, recursion depth not an issue if we use iterative BFS/DFS.
But wait, sample input in problem statement is something else? Actually given in problem statement:
Input:
6 0 6
2 1 2
2 3 4
2 5 6
2 3 2
2 5 3
1 1
Output:
4
Let's simulate:
n=6, m=0 (no initial edges), q=6.
Queries:
1: 2 1 2 -> merge 1 and 2. Initially each node isolated (diam=0). Merge: new_d = max(0,0, (0+1)//2=0 + (0+1)//2=0 +1=1) => 1. So component {1,2} diameter=1.
2: 2 3 4 -> merge 3 and 4 -> new component {3,4} diameter=1.
3: 2 5 6 -> merge 5 and 6 -> component {5,6} diameter=1.
4: 2 3 2 -> merge component of 3 (which is {3,4}) with component of 2 (which is {1,2}). So diameters: d1=1, d2=1 => rad1=1, rad2=1? Actually (1+1)//2 = 1? Wait d=1 => (1+1)//2=1. So rad=1. new_d = max(1,1,1+1+1=3) => 3. So component {1,2,3,4} diameter=3.
5: 2 5 3 -> merge component {5,6} (d=1) with component containing 3 (which is {1,2,3,4} d=3). d1=3, d2=1. rad1 = ceil(3/2)=2, rad2=1. sum=2+1+1=4. new_d = max(3,1,4)=4.
6: 1 1 -> output diameter of component containing 1 = 4. Matches output.
Thus solution works.
Now we need to ensure that we correctly compute initial diameters for components that may have more than one node. Since m could be up to n-1 (but less than n). So there may be components with many nodes. BFS twice works.
Potential pitfalls: DSU union operations for initial edges: we need to union them to maintain connectivity for queries. However, we also compute diameters later via BFS. But note: The DSU after unions will reflect the connectivity after initial edges, but when we compute diameters via BFS, we use the adjacency list only (which includes the initial edges). That's fine. However, DSU's structure after unions might have different representatives than BFS components. But that's okay; we just need DSU for merging queries. After we compute diameters, we need to assign the diameter to the DSU root. For each component, we need to find the DSU root of any node in that component. That will be the representative of that set. However, if we performed DSU unions during reading edges, the DSU's sets match the connectivity exactly, because the edges are the same. So it's consistent.
But there is a subtlety: In BFS, we traverse using adjacency list which contains only initial edges. In DSU, we also union only those edges. So they match.
Now, after processing initial diameters, we need to process q queries. Type 2 queries will perform unions and update diameters. There's no need to modify adjacency list or actual graph; we are just maintaining DSU with diameter values.
Thus solution.
Now, we need to implement efficiently.
Implementation steps:
Read n, m, q.
Initialize adjacency list g = vector<vector>(n+1).
Initialize DSU arrays: parent[n+1], rank[n+1], dia[n+1] (maybe initially 0). Also perhaps size array if needed for union by size, but rank is fine.
For each of m edges:
read a, b.
g[a].push_back(b); g[b].push_back(a);
unionSets(a,b) (but we may not compute diameter yet). Use DSU union function to merge sets.
After reading all edges, compute initial diameters as described using BFS with timestamp technique.
arrays: seen (int) of size n+1 initialized to 0, dist (int) size n+1 (could be reused).
timestamp = 0.
for i=1 to n:
if seen[i]==0:
// first BFS to find farthest u
timestamp++;
queue q; q.push(i); seen[i]=timestamp; dist[i]=0; int u=i;
while (!q.empty()){
int v=q.front(); q.pop();
for int to: g[v]:
if seen[to]!=timestamp:
seen[to]=timestamp; dist[to]=dist[v]+1; q.push(to);
if dist[to]>dist[u] u=to;
}
// second BFS from u to compute diameter
timestamp++;
q=queue(); q.push(u); seen[u]=timestamp; dist[u]=0; int maxd=0;
while (!q.empty()){
int v=q.front(); q.pop();
for int to: g[v]:
if seen[to]!=timestamp:
seen[to]=timestamp; dist[to]=dist[v]+1; q.push(to);
if dist[to]>maxd) maxd=dist[to];
}
// set diameter for DSU root
int r = find(i); // DSU find
dia[r] = maxd;
Note: The BFS uses seen array with timestamp, and we start with seen[i]==0 to indicate not visited at all. After second BFS, seen values will be the latest timestamp, which is >0, so outer loop skips them.
Now process q queries:
For each query:
read type.
if type == 1:
read x; root = find(x); print dia[root];
else:
read x, y; unite(x, y); // DSU union that updates dia.
Now we must be careful: When we do DSU union for initial edges, we didn't set diameters. After step 4, dia array is still zero for all roots. Then in step 5, we assign dia for each root. However, after unions in step 4, the DSU sets may have multiple nodes; we will compute diameters per component and assign to the root. But we must ensure that we assign to the correct root after unions. That is fine.
But one more nuance: In step 5, we iterate over nodes i from 1..n, and for each unvisited node (by BFS), we compute component's diameter. However, we rely on DSU's find to get root. But if we call find(i) after we have computed the component's diameter, that's fine. However, there's a subtle case: DSU union operations might have been done with path compression, but some nodes might have parents that are not fully compressed. But find will compress path. So it's fine.
But we must ensure that dia for each root is set exactly once per component, not multiple times. Since we only assign dia[r] = maxd when we encounter the first node of each component (i not seen). However, there is possibility that two different BFS components might correspond to the same DSU set if the DSU union has not fully merged? Actually DSU unions ensure connectivity; if we have performed unions for all initial edges, the DSU sets correspond exactly to connected components. Since BFS also finds connected components based on adjacency list, they should match exactly. So for each DSU set, there is exactly one BFS component. So we assign dia[root] once.
Now, after we compute diameters and assign to roots, we need to be cautious: The DSU's union operations in step 4 might have set parent relationships but we haven't updated dia for those unions. For initial edges, the diameters should be computed from the actual tree, not by merging formula (since the edges are given, not necessarily connecting centers). But we compute diameters from the actual graph, which is correct. So after step 5, dia[root] holds the actual diameter of the component. So no need to simulate merges for initial edges.
Now type 2 queries: We need to perform union that simulates merging components by adding an edge that minimizes new diameter. The DSU union must update the diameter accordingly using formula.
Thus solution seems straightforward.
Let's think about correctness thoroughly. Are there any cases where the diameter of a tree is not simply the maximum of distances computed via BFS? That is correct.
One subtlety: The problem defines length of a path as (k-1), i.e., number of edges. So diameter in edges count is what we need. BFS distances in edges count give the correct measure.
Another subtlety: In the merging process, when we compute new diameter as max(d1, d2, (d1+1)//2 + (d2+1)//2 + 1), we must ensure that the integer division is correct for ceil(d/2). Indeed, (d+1)//2 works for non-negative integer d.
Now we should also consider if there are any other factors that might affect the minimal diameter after merging. For example, if we connect not exactly the centers but some nodes close to centers, the cross distance might be less than rad1+rad2+1? The minimal possible max(ecc(u), ecc(v)) when choosing u and v? Actually the cross distance we care about is max_{a in T1, b in T2} dist(a,b). That is equal to ecc_T1(u) + 1 + ecc_T2(v) if we connect u and v. To minimize the overall diameter, we want to minimize max( d1, d2, ecc_T1(u)+1+ecc_T2(v) ). Since d1 and d2 are fixed, we want to minimize the third term. The minimal possible value of ecc_T1(u)+1+ecc_T2(v) is r1+1+r2, achieved by picking u as a center of T1 and v as a center of T2. So that's optimal.
One might ask: Could the new diameter be larger than max(d1, d2, r1+r2+1) even if we connect centers? Possibly if the path that goes through the new edge and also uses some other part of the trees yields a longer path that is not captured by the formula? Actually any path that goes from a node in T1 to a node in T2 must go through the new edge (u,v). So its length is dist_T1(a,u) + 1 + dist_T2(v,b). The maximum over a,b is max_{a} dist_T1(a,u) + 1 + max_{b} dist_T2(v,b) = ecc_T1(u) + 1 + ecc_T2(v). So that's the maximum cross distance. So if we set u and v as centers, cross max = r1+1+r2. And any internal path within T1 or T2 remains at most d1 or d2. So overall diameter = max(d1, d2, r1+1+r2). So it's exactly that.
Thus formula holds.
Now, after we merge using this formula, the resulting tree's diameter is new_d. However, is the radius of the new tree necessarily ceil(new_d/2)? Yes, always. So future merges can rely on diameters only.
Thus DSU with diameter works.
Now time to implement.
Complexities: BFS using queue and adjacency list will traverse each edge twice (once per direction). So O(n + m). DSU operations O(alpha(n)). Queries O(q). So total O((n+m+q) log* n) but actually alpha is inverse Ackermann, basically constant.
Memory: adjacency list O(n+m). DSU arrays O(n). seen and dist O(n). Fine.
Potential issues: The BFS method with timestamps: we need to allocate seen array of size n+1 and dist array. Since we use timestamps, we can use vector seen(n+1, 0) and int timestamp = 0; For each BFS we increment timestamp and mark visited nodes by setting seen[node] = timestamp. This avoids resetting arrays each time.
But careful: For second BFS, we increment timestamp again, so we can reuse the same seen array with a different timestamp, marking nodes again. That's fine.
Now, about the DSU: we need to store dia[] for each root. But after union, the root might change, and we need to ensure that when we query find(x), we get the root and its diameter is stored correctly. That is fine.
Now we need to pay attention to integer types: n up to 300k, diameters can be up to n-1. So int is fine.
Now about I/O: many queries, use scanf/printf or fast ios.
Implementation details in code:
We'll write:
struct DSU {
vector parent, rank, dia;
DSU(int n) : parent(n+1), rank(n+1,0), dia(n+1,0) {
for(int i=0; i<=n; ++i) parent[i]=i;
}
int find(int x) {
return parent[x]==x ? x : parent[x]=find(parent[x]);
}
void unite(int a, int b) {
a = find(a); b = find(b);
if (a == b) return;
if (rank[a] < rank[b]) swap(a,b);
parent[b] = a;
if (rank[a] == rank[b]) rank[a]++;
int new_dia = max({dia[a], dia[b], (dia[a]+1)/2 + (dia[b]+1)/2 + 1});
dia[a] = new_dia;
}
};
But careful: In unite, after merging, we should also update rank. That's okay.
Now for initial diameter computation:
We have adjacency list g (vector<vector>). We'll also have DSU dsu(n).
Read m edges, add to g, and dsu.unite(a,b). (Note: we must define unite before we compute diameters. So dsu.unite should be available.)
Then after reading, compute diameters:
vector seen(n+1, 0), dist(n+1, 0);
int ts = 0;
for(int i=1; i<=n; ++i) {
if (seen[i]==0) {
// first BFS to find farthest
ts++;
queue q;
q.push(i);
seen[i] = ts;
dist[i] = 0;
int u = i;
while (!q.empty()) {
int v = q.front(); q.pop();
for (int to : g[v]) {
if (seen[to] != ts) {
seen[to] = ts;
dist[to] = dist[v] + 1;
q.push(to);
if (dist[to] > dist[u]) u = to;
}
}
}
// second BFS from u
ts++;
q = queue(); // clear queue
q.push(u);
seen[u] = ts;
dist[u] = 0;
int maxd = 0;
while (!q.empty()) {
int v = q.front(); q.pop();
for (int to : g[v]) {
if (seen[to] != ts) {
seen[to] = ts;
dist[to] = dist[v] + 1;
q.push(to);
if (dist[to] > maxd) maxd = dist[to];
}
}
}
// set diameter
int root = dsu.find(i);
dsu.dia[root] = maxd;
}
}
One catch: In the BFS, we use seen array to mark visited. However, after first BFS, we set seen for all nodes in the component to timestamp ts (first BFS). Then for second BFS, we increment ts and mark again. So after we exit, those nodes will have seen set to the second ts. The outer loop condition if (seen[i]==0) ensures we don't process again. That works because seen[i] is now non-zero.
Now after computing diameters, we process queries: