Another task about trees
Consider a graph with vertices, initially devoid of edges. You are tasked with handling queries, which are of two types:
Add an edge from vertex to vertex , ensuring that and belong to different trees, and that is the root of its tree.
Check if two vertices and are part of the same tree.
Solution
We will use the Union-Find data structure with path compression to efficiently manage these operations:
int n, m, l[NMAX]; int calc_leader (int v) { if (l[v] != v) l[v] = calc_leader(l[v]); return l[v]; } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++) l[i] = i; for (int i = 1; i <= m; i++) { int x, y, z; scanf("%d%d%d", &z, &x, &y); if (z == 1) l[y] = x; else if (calc_leader(x) == calc_leader(y)) printf("YES\n"); else printf("NO\n"); } }
Your task is to design a test case that causes this solution to execute for an extended period. Specifically, the number of calls to the function calc_leader
should be at least .
Input
The input consists of two integers and (, , ).
Output
Produce lines of output. The -th line should be formatted as if the -th query is to add an edge from vertex to vertex , or if it is to check whether vertices and are in the same tree.