As Sherlock Holmes was investigating another crime, he found a certain number of clues. Also, he has already found direct links between some of those clues. The direct links between the clues are mutual. That is, the direct link between clues A and B and the direct link between clues B and A is the same thing. No more than one direct link can exist between two clues.
Of course Sherlock is able to find direct links between all clues. But it will take too much time and the criminals can use this extra time to hide. To solve the crime, Sherlock needs each clue to be linked to all other clues (maybe not directly, via some other clues). Clues A and B are considered linked either if there is a direct link between them or if there is a direct link between A and some other clue C which is linked to B.
Sherlock Holmes counted the minimum number of additional direct links that he needs to find to solve the crime. As it turns out, it equals T.
Please count the number of different ways to find exactly T direct links between the clues so that the crime is solved in the end. Two ways to find direct links are considered different if there exist two clues which have a direct link in one way and do not have a direct link in the other way.
As the number of different ways can turn out rather big, print it modulo k.
Input
The first line contains three space-separated integers n, m, k (1 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ k ≤ 109) — the number of clues, the number of direct clue links that Holmes has already found and the divisor for the modulo operation.
Each of next m lines contains two integers a and b (1 ≤ a, b ≤ n, a ≠ b), that represent a direct link between clues. It is guaranteed that any two clues are linked by no more than one direct link. Note that the direct links between the clues are mutual.
Output
Print the single number — the answer to the problem modulo k.
Examples
Input
2 0 1000000000
Output
1
Input
3 0 100
Output
3
Input
4 1 1000000000
1 4
Output
8
Note
The first sample only has two clues and Sherlock hasn't found any direct link between them yet. The only way to solve the crime is to find the link.
The second sample has three clues and Sherlock hasn't found any direct links between them. He has to find two of three possible direct links between clues to solve the crime — there are 3 ways to do it.
The third sample has four clues and the detective has already found one direct link between the first and the fourth clue. There are 8 ways to find two remaining clues to solve the crime.
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 parse the problem: Sherlock has n clues, some pairs already have direct links (edges). The graph is undirected, simple. He wants the final graph to be connected (so that every clue is linked to every other, via paths). He already counted the minimum number of additional direct links needed to make the graph connected. That number equals T. He needs to count the number of different ways to add exactly T edges (i.e., choose a set of exactly T edges among the non-existing edges) such that after adding them, the graph becomes connected. And we output count modulo k (k up to 1e9, not necessarily prime).
Important: T is defined as the minimum number of additional edges needed to make the graph connected. So T is the number of edges required to make the graph connected, given current connected components. Typically, to connect a graph with c components (c>0), we need at least c-1 edges (connecting the components). Indeed, if we have c connected components, the minimum additional edges to make the graph connected is c-1, assuming no extra edges needed within components. However, is it always c-1? Yes, because you can connect components in a tree structure. So T = c-1, where c is the number of connected components in the initial graph (including isolated vertices? Yes, isolated vertices are components of size 1). But careful: If the graph is already connected (c=1), then T=0? Then we need to count number of ways to add exactly 0 edges such that graph is connected: that would be 1 way (do nothing). And indeed the problem says "Sherlock Holmes counted the minimum number of additional direct links that he needs to find to solve the crime. As it turns out, it equals T." So T is the minimum needed. That implies if the graph is already connected, T=0. So we need to count ways to add exactly T edges to make it connected. And T is computed as (number of components) - 1.
But wait: Could there be a case where T is larger than c-1 because some components are already connected via paths? No, the minimum edges needed to connect a graph with c components is exactly c-1. So indeed T = c-1.
Thus we have: Given an undirected graph with n vertices, m edges, and c connected components. T = c-1.
Now we need to count the number of sets of exactly T edges (which are not already present) such that after adding those edges, the graph becomes connected.
We need to output that number modulo k.
Constraints: n up to 1e5, m up to 1e5, so we can compute components via DSU or BFS/DFS.
Now the counting: The total number of possible edges in a complete graph on n vertices is N = n*(n-1)/2. The already existing edges are m, so number of missing edges is M = N - m.
We need to choose exactly T edges from these M missing edges such that the resulting graph is connected.
We need to compute the number of ways to add T edges to connect c components into a single connected component.
This is a classic combinatorial problem: Given a graph with components of sizes s1, s2, ..., sc (with sum = n), count the number of ways to add exactly T = c-1 edges (so a forest that connects all components) such that the resulting graph is connected. But careful: The edges we add are only between vertices from different components (because if we add an edge within a component, it wouldn't help reduce the number of components, and to achieve connectivity with exactly c-1 edges, we must add exactly c-1 edges that connect components, and no edges within components, because any extra edge inside a component would be wasteful and would make total added edges > c-1, but we are required to add exactly T edges. So indeed, any set of T edges that makes the graph connected must consist exclusively of edges that go between different components, because if we include any edge inside a component, then to still have connectivity we would need at least c edges? Let's reason: Suppose we have c components initially. Adding an edge between two vertices in the same component does not change the number of components; it remains c. To eventually have a single component, we need to reduce the number of components from c to 1. Each edge that connects two different components reduces the number of components by exactly 1 (merging them). Thus the minimum number of edges required is c-1, and each such edge must connect two different components. If we add any edge that is inside a component, it does not reduce the component count, so to still achieve connectivity we would need at least c edges: c-1 edges to connect components plus the extra intra-component edge (which does nothing). But the total number added is exactly T = c-1, so we cannot have any intra-component edge; all T edges must be inter-component edges.
Therefore, the problem reduces to: Count the number of ways to choose exactly c-1 edges from the set of all possible inter-component edges (i.e., edges whose endpoints belong to different components) such that the chosen edges connect all components into one. This is essentially the number of spanning trees in the complete graph of components, where each "component" is a super-node, but each edge between components actually corresponds to many possible edges between specific vertices in those two components. More precisely, if we have components of sizes s1, s2, ..., sc, then the total number of possible edges between component i and component j is s_i * s_j. For a set of c-1 edges to connect all components, they must form a tree on the components. For each tree on the component set, the number of ways to realize it (i.e., choose specific vertex pairs for each tree edge) is product over edges (u,v) in the tree of (s_u * s_v). Because each inter-component edge can be any pair of vertices from the two components.
Thus the total number we need is: sum over all trees on c labeled nodes (components are labeled by index) of ∏_{(i,j) in tree} (s_i * s_j). This is a well-known combinatorial value: It equals (s1 s2 ... sc) * (n^{c-2})? Wait, there's a known formula for the number of spanning trees in a complete graph with weighted edges? Actually, there is a formula: For a complete graph with vertex weights (s_i), the number of trees where each edge between i and j contributes factor s_i * s_j, sum over all trees, equals (s1 s2 ... sc) * n^{c-2}. Let's check.
We recall the matrix-tree theorem: For a graph with Laplacian L, the number of spanning trees = any cofactor. For a complete graph on c vertices where edge weights are w_{ij} (maybe the product s_i s_j), the Laplacian entries: L_{ii} = sum_{j≠i} w_{ij} = s_i * (sum_{j≠i} s_j) = s_i * (n - s_i). Off-diagonal: L_{ij} = -w_{ij} = - s_i s_j.
We want the number of spanning trees of this weighted graph, i.e., sum over trees ∏{(i,j)∈T} w{ij}. That is exactly the weighted number of spanning trees. There is a known result: For such a weight matrix, the number of spanning trees = (s1 s2 ... sc) * n^{c-2}. Let's test with small examples:
c=1: There is only one component? Then T=0, number of ways = 1. The formula would give (product of s_i) * n^{-1}? Actually n^{c-2}=n^{-1}? That's not defined. But c=1 is a special case: T=0, number of ways = 1 (do nothing). Our counting of trees would be trivial: there is exactly one "tree" with no edges. We can treat separately.
c=2: components of sizes s1, s2, n = s1+s2. Number of ways to connect them with exactly 1 edge: the number of possible inter-component edges = s1 * s2. So answer = s1s2. The formula: (s1 s2) * n^{0} = s1s2. Yes.
c=3: components sizes s1,s2,s3. Number of trees on 3 nodes: there are 3 possible trees (each tree is a star or a path). For each tree, product of edge weights: e.g., tree connecting 1-2 and 2-3 gives (s1 s2)*(s2 s3) = s1 s2^2 s3. Similarly other trees give s1^2 s2 s3, s1 s2 s3^2. Sum = s1 s2 s3 (s1 + s2 + s3) = s1 s2 s3 * n. According to formula: (s1 s2 s3) * n^{1} = s1 s2 s3 * n. Yes.
c=4: We can test: sizes s1..s4. Sum = n. Weighted tree number = (s1 s2 s3 s4) * n^{2}. That would be s1 s2 s3 s4 * n^2. Let's compute using matrix-tree? It seems plausible. Indeed, there is a known result: For a complete graph K_c with edge weight w_{ij} = x_i x_j, the number of spanning trees = (x_1 x_2 ... x_c) * (x_1+...+x_c)^{c-2}. That's exactly our case with x_i = s_i. Because w_{ij} = s_i s_j. So by the matrix-tree theorem, the cofactor of Laplacian yields that. One can prove using the fact that the Laplacian can be expressed as D * (n I - s s^T?) Actually, L = diag(s_i * (n - s_i)) - off diag(s_i s_j). This can be written as: L = D - S, where D_{ii} = s_i * n - s_i^2, and S_{ij} = s_i s_j (i≠j). But there is a known formula: For a rank-1 modification, the eigenvalues are: one eigenvalue 0, and others equal to n * (vector?) Let's compute: L = n * diag(s_i) - s s^T? Check: diag(s_i) has entries s_i. Then n * diag(s) gives diagonal entries n s_i. s s^T gives matrix with entries s_i s_j. So n*diag(s) - s s^T gives diagonal: n s_i - s_i^2, off-diagonal: - s_i s_j. That's exactly L because L_{ii} = s_i * (n - s_i) = n s_i - s_i^2, and L_{ij} = - s_i s_j. Yes! So L = n * diag(s) - s s^T, where s is the column vector of sizes.
Now, the number of spanning trees of a weighted complete graph with these weights is the any cofactor of L. Since L has rank c-1? Because n * diag(s) - s s^T. Using matrix determinant lemma, we can compute the cofactor. Indeed, we can compute the determinant of the matrix obtained by deleting row i and column j. There is known result: For any connected weighted graph, the number of spanning trees = (1/ n) * product_{i=1}^{c} λ_i? But specifically, for this L, the eigenvalues: one eigenvalue is 0, and the other c-1 eigenvalues are n * s_i? Not exactly. Let's compute: Since L = n diag(s) - s s^T. Consider vector v = (1,1,...,1) scaled appropriately? Actually, note that diag(s) is not a scalar matrix. There's a known formula: The number of spanning trees = (s1 s2 ... sc) * n^{c-2}. We'll trust it.
Thus the number of ways to add exactly c-1 edges (a set of edges that connects all components) is equal to (product_{i=1}^{c} s_i) * n^{c-2}.
But wait, is that correct for all cases? Let's test with sample 2: n=3, m=0. Then initial graph: 3 isolated vertices => components: sizes [1,1,1], c=3. T = 2. product(s_i)=111=1, n^{c-2}=3^{1}=3, so answer =3. Sample output is 3. Good.
Sample 3: n=4, m=1, edge (1,4). So initial graph: vertices: 1 and 4 are connected? They have an edge, so they form a component of size 2. Vertices 2 and 3 are isolated? So components: one of size 2, and two singles: sizes [2,1,1] (c=3). T = 2. product = 211=2, n^{1}=4, total = 8. Sample output 8. Good.
But there is a subtlety: The problem says "Sherlock Holmes counted the minimum number of additional direct links that he needs to find to solve the crime. As it turns out, it equals T." That T is computed from the current graph. Then we need to count the number of ways to find exactly T direct links so that after adding them the graph becomes connected. So indeed we are counting sets of exactly T edges that make the graph connected. And we've argued that these must be inter-component edges forming a tree on the components.
But what about the possibility that adding an intra-component edge could still lead to connectivity with exactly c-1 edges if we also skip some inter-component edge? That is, suppose we have components. To achieve a connected graph with exactly c-1 added edges, the final graph must have n vertices and m + (c-1) edges. Is it possible that the final graph is connected but contains an intra-component edge? Consider we have c components initially. If we add any intra-component edge, the number of components remains c. To become connected, we need to reduce component count to 1. Each inter-component edge reduces count by at most 1. So we need at least c-1 inter-component edges. If we include any intra-component edge, then total edges added = (c-1) would consist of (c-2) inter-component edges and 1 intra-component edge. After adding (c-2) inter-component edges, we would have at least 2 components remaining (since each inter-component merge reduces component count by 1). Actually, starting with c components, after adding k inter-component edges that connect distinct components (without creating cycles among components? But if they are not forming a tree, they could merge more than two at a time? Actually, each inter-component edge always connects two different components, merging them into one. So after adding t inter-component edges, the number of components becomes c - t, provided these edges are all between distinct components and they do not create cycles? If they connect components that are already in the same component, that would be an intra-component edge in the merged structure; but initially they are from different components, so the first edge merges two components. Second edge might connect two components that are still separate or could connect a component to a component that already merged? That's still merging two currently separate components, reducing component count by 1. So after t inter-component edges, component count = c - t, as long as each edge connects vertices from two different current components. But if we add edges that eventually create a cycle among components, that would not reduce component count further; but that can happen only if we add an edge between two vertices that are already in the same component after some merges. That would be an intra-component edge at the time of addition, but if we add edges sequentially, the moment we add an edge between two vertices that are already in the same component, it does not reduce component count. So to end with component count 1, we must have at least c-1 inter-component edge additions that each reduce count by 1. If we add any edge that does not reduce count, then we would need more than c-1 total edges to get to 1 component, because we would have fewer inter-component merges. So with exactly c-1 edges total, we must have exactly c-1 inter-component edges, and zero intra-component edges. So our reasoning holds.
Thus the counting is exactly as described: number of ways to choose a set of c-1 edges from the inter-component edges such that they connect all components. This number is (∏ s_i) * n^{c-2}.
But we must be careful: This formula assumes that we treat each component as a labeled node (which they are, indices matter), and we count each tree exactly once, and for each tree, the product of s_i s_j over edges. That yields the sum.
Now, is there any scenario where the graph already has some inter-component edges? Actually, there might be multiple edges already present between components? Wait, the graph initially may have edges only within components? By definition of components, there are no edges between different components initially. So the set of inter-component edges is exactly all pairs of vertices from different components that are not already edges? But the definition of components is that there is no path between vertices in different components, meaning there is no edge between them. So indeed, initially there are zero edges between different components. Because if there was an edge between two vertices in different components, they would be in the same component (since the edge connects them). So by definition of connected components, there are no edges between different components. So all inter-component edges are missing edges. Good.
Thus the set of possible edges to add is exactly all pairs of vertices from different components, which total = total missing edges? Actually missing edges also include edges inside components that are not present; but those are irrelevant as we argued. So the count is exactly the number of ways to pick a connecting tree.
Hence answer = (∏_{i=1}^{c} s_i) * n^{c-2} modulo k.
But wait, what about the case where the graph is already connected (c=1)? Then T=0, and the answer should be 1 (the empty set). Our formula would give product s_i = n, and n^{c-2}= n^{-1}? Not defined. So we handle c=1 separately: answer = 1 (since there is exactly one way: add no edges). Or we could define 0 edges needed, and the only set is empty. That matches sample? No sample with c=1. So we need to handle.
Now, we have n up to 1e5, m up to 1e5. So we can compute component sizes using DSU or DFS. The number of components c can be up to n.
We need to compute product of sizes modulo k, and also compute n^{c-2} modulo k. However, k is not necessarily prime, and can be up to 1e9. The product may be large; we can compute modulo k. But careful: Since k is not prime, and we only need result modulo k, we can compute mod as we multiply.
But there is a catch: The formula (∏ s_i) * n^{c-2} may not be integer modulo k? It's integer, but we just compute mod.
But wait, is it always correct? Let's double-check the combinatorial derivation thoroughly.
We have c components with sizes s_1,...,s_c. All possible inter-component edges are s_i * s_j for each unordered pair (i,j). We need to count subsets E' of exactly c-1 edges from these possible edges, such that the graph (with vertices 1..n and edges original within components + E') is connected. Since original edges already ensure connectivity within each component, the overall connectivity condition is that the graph of components (contracting each component to a supernode) becomes connected via the added edges. That is, the added edges must induce a connected graph on the component set. Moreover, they must be exactly c-1 edges, so they must form a spanning tree on the component graph (since any connected graph on c nodes has at least c-1 edges, and exactly c-1 implies it's a tree). And indeed, if they formed a connected graph with cycles, it would have >c-1 edges. So they must form a tree.
Thus we need to count the number of trees T on the set of c labeled nodes, where each edge (i,j) in the tree can be realized by any of the s_i * s_j specific edges between the actual vertices of those components. And choices for different tree edges are independent (since edges are distinct vertex pairs, and no overlap? Could there be overlap in the sense of using the same vertex in two edges? That's allowed; we can have multiple edges incident to the same vertex within a component. The edges are between distinct vertices (simple graph). Since we are only adding edges that are currently missing, and vertices within a component are not all connected? Actually, inside a component, there may already be edges, but we are adding edges between components only. So each added edge is between a specific vertex in component i and a specific vertex in component j. It's possible to add two edges that share a vertex in component i? Yes, because a vertex can have multiple edges to different components. That's allowed; the graph remains simple as long as we don't add duplicate edges between the same pair of vertices, but that would be counted separately? Actually, in a tree on components, if component i has degree d_i, then we will need to select d_i distinct vertices? Not necessarily distinct: A single vertex in component i can be incident to multiple added edges connecting to different components. That is allowed; there's no restriction that a vertex cannot have multiple added edges. So when counting realizations for a given tree, the product s_i * s_j for each edge is correct, because for each edge (i,j), we independently choose a vertex from component i and a vertex from component j. However, are these choices independent across edges? If two edges share component i, the choices of vertices in component i for those edges are independent; they could be the same vertex or different. That's fine because the graph can have multiple edges incident to the same vertex. There is no restriction that the chosen edges must be distinct pairs of vertices; they are automatically distinct because each edge is defined by a pair (u,v). If we pick the same vertex u in component i for two different edges (i,j) and (i,k), that's allowed; those are two distinct edges (u with some v in j, and u with some w in k). There's no conflict because they involve different other vertices. So independence holds.
Thus the number of realizations for a fixed tree on component nodes is exactly ∏{edges (i,j)} (s_i * s_j) = (∏{i=1}^c s_i^{deg_T(i)}) where deg_T(i) is degree of component i in the tree. Since for each vertex i, its size factor s_i appears deg_T(i) times. So product over edges gives ∏_i s_i^{deg_T(i)}. Then summing over all trees T gives ∑_T ∏_i s_i^{deg_T(i)}. There is known formula: ∑_T ∏_i s_i^{deg_T(i)} = (∏_i s_i) * (∑_i s_i)^{c-2} = (∏ s_i) * n^{c-2}. This follows from Kirchhoff's matrix-tree theorem or from the fact that the number of spanning trees with weights is given by that. We can also consider the "Cayley's formula" generalization: For complete graph with vertex weights, the number of trees with a given degree sequence can be expressed via the multinomial coefficient. Actually, there is known result: The number of trees on labeled vertices where vertex i has degree d_i is given by (c-2)! / ∏(d_i-1)!. Summing over degree sequences weighted by ∏ s_i^{d_i} yields (∏ s_i) * (∑ s_i)^{c-2} as a consequence of the generating function. Indeed, we can write:
∑{T} ∏{i} s_i^{deg_T(i)} = (∏ s_i) * ∑{d_1+...+d_c = 2(c-1), each d_i≥1} ( (c-2)! / ∏ (d_i-1)! ) ∏ s_i^{d_i-1} = (∏ s_i) * (∑ s_i)^{c-2} by the multinomial theorem. Because (∑ s_i)^{c-2} expands to ∑{(e_1+...+e_c = c-2)} (c-2)!/(∏ e_i!) ∏ s_i^{e_i}. Let e_i = d_i-1, then d_i ≥ 1, sum e_i = (c-2). So exactly. Thus formula is correct.
Hence answer = (∏ s_i) * n^{c-2} for c >= 2, and 1 for c = 1.
So the problem reduces to: compute connected components sizes, compute product of sizes mod k, compute n^(c-2) mod k, multiply mod k, output.
But wait, there is another nuance: T is defined as the minimum number of additional direct links needed. So if the graph is already connected, T=0. Then the answer is 1 (empty set). That matches our separate case.
But what if there are isolated vertices and components of size >1? The formula still works.
Now we need to consider the possibility that there might be already some inter-component edges? As argued, no, because components are maximal connected subgraphs, so there can be no edges between different components. However, what about the scenario where initially there are multiple edges between components? That cannot happen because if there is any edge between two vertices in different components, they would be in the same component. So it's impossible.
Thus the solution seems trivial: compute component sizes, if c=1 answer=1, else answer = (∏ s_i) * (n)^{c-2} mod k.
But is there any catch? Let's read the problem statement again: "Sherlock Holmes counted the minimum number of additional direct links that he needs to find to solve the crime. As it turns out, it equals T." So T is determined from the initial graph. Then "Please count the number of different ways to find exactly T direct links between the clues so that the crime is solved in the end." So we are to count the number of sets of exactly T edges (additions) that result in a connected graph. However, we assumed that the only way to achieve connectivity with exactly T edges is to add edges that connect components in a tree. But what if the initial graph has some edges within components that are not enough to make them connected? Wait, components are defined as connected components, so they are connected by definition. So each component is already connected internally. So adding an edge inside a component would create a cycle, but would not help connecting components. So indeed.
Thus answer is simple.
But why is the problem placed perhaps in a contest? Might be that it's indeed a simple combinatorial formula, but the tricky part is that k is not necessarily prime and n up to 1e5, but product of sizes could be huge, but we compute modulo k. However, we also need to compute n^{c-2} mod k. c could be up to 1e5, so exponent could be large. We can compute fast exponentiation modulo k. But careful: exponent c-2 can be up to ~1e5, which is fine.
But there is another nuance: The answer might be 0 mod k for some k, but that's acceptable.
But let's double-check sample 3: n=4, components sizes: after edge (1,4), we have component {1,4} size 2, and two isolated vertices: sizes 1 and 1. Product=2, n^{c-2}=4^{1}=4, product=8. Works.
Now test more cases: Suppose n=5, initial edges: (1,2),(3,4) => components: sizes [2,2,1] (c=3). T=2. According to formula: product = 221=4, n^{1}=5, answer=20. Let's brute check: Total possible inter-component edges: between component A (size2) and B(size2): 22=4 edges, between A and C: 21=2, between B and C: 21=2. We need to pick 2 edges that connect all three components. The possibilities: Trees on 3 nodes: 3 possible trees. For tree with edges (A-B) and (A-C): #realizations = (s_A * s_B) * (s_A * s_C) = (22)(21)=42=8. Similarly (A-B) and (B-C): = (22)(21)=42=8. (A-C) and (B-C): = (21)(21)=2*2=4. Sum = 20. Yes.
Now what about n=100000, many components? The product of sizes might be huge but we can compute mod.
But is there any other complexity? Possibly the graph may have multiple components of size 1? That's fine.
Edge Cases: c=0? Not possible because n>=1, so at least one component. c=1 => T=0 => answer 1.
Now, check if there could be self-loops? Input says a != b, so no.
Thus solution: read n,m,k; build graph or DSU to find component sizes.
We need to compute component sizes efficiently. Since n,m up to 1e5, we can use adjacency list and BFS/DFS, or DSU. DSU is straightforward: initialize parent for n vertices. For each edge (a,b), union them. Then after processing all edges, we find sizes: for each root, count how many vertices. Then collect sizes.
We also need to compute the number of components c = number of roots.
If c == 1: answer = 1 % k.
Else: compute product = ∏ s_i mod k.
We need to compute n^{c-2} mod k using fast exponentiation.
Multiply product * n^{c-2} mod k.
But careful: There might be an overflow in intermediate multiplication? Use 64-bit integer (long long) if product < 2^63? k up to 1e9, product mod k will be < k, but intermediate multiplication product * (n^{c-2} mod k) could be up to (k-1)^2 ~ 1e18, which fits in 64-bit signed (max ~9e18). So we can do (product * pow_mod) % k using 64-bit.
But we must compute product modulo k from the sizes. Sizes can be up to n=1e5. Multiplying many numbers mod k: use modulo at each multiplication.
Potential pitfalls: If k=1, answer is 0 (since modulo 1). So we can handle modulo operation straightforward.
Now, is there any chance that the answer is not given by this formula because the set of edges added must be exactly T edges, but perhaps there exist sets of T edges that include some intra-component edges but still achieve connectivity because the intra-component edge could be used to replace an inter-component edge? That doesn't make sense: Starting with c components, after adding any set of edges, the number of components can only decrease when we add inter-component edges. The final graph is connected if and only if the added edges connect all components. Suppose we add e_inter inter-component edges and e_intra intra-component edges, with total T = e_inter + e_intra = c-1. After adding e_inter inter-component edges, the number of components becomes c - e_inter' where e_inter' is the number of inter-component edges that actually merge distinct components (some inter-component edges might become redundant if they connect vertices that are already in the same component due to previous merges). But careful: When we add edges in a set, we consider the final graph; we don't have an order. However, the final graph will have some number of components. Initially we have c components. Adding any edge between two vertices from different components will merge those components into one (if they are still separate in the final graph). But if we add multiple edges among the same set of components, some edges may become "redundant" in the sense that they connect vertices within the same final component, but that final component is formed by merging via other edges. So to achieve a final single component, we need that the graph of components (where we contract each initial component) becomes connected via the added edges. In other words, the added edges must contain a spanning tree on the component graph. That spanning tree uses exactly c-1 edges, all of which are between different initial components. Any additional edge beyond that spanning tree (including intra-component edges or extra inter-component edges) would increase total edge count beyond c-1. But we only add exactly c-1 edges. So the set must be exactly a spanning tree on the component graph, and cannot contain any edge that is not part of that tree? Actually, could the set contain an edge that is intra-component (within an initial component) but still the set of edges as a whole connects the components? If we include an intra-component edge, then we have at most c-2 inter-component edges (since total edges = c-1). But then the inter-component edges must connect c components into one component. However, with only c-2 inter-component edges, the component graph can have at most c - (c-2) = 2 components remaining (since each inter-component edge reduces the number of components by at most 1). Actually, the component graph after adding the inter-component edges (considering only those edges) will have some number of connected components among the initial components. If we have exactly c-2 inter-component edges that form a forest, the number of components in the contracted graph would be c - (c-2) = 2 (since a forest on c nodes with c-2 edges has exactly 2 components). Then after adding the intra-component edge, it does not connect these two remaining components because it's inside an initial component, which belongs to one of the two super-components. So the final graph still has two components (the two groups of initial components). Thus it's not connected. Could there be a scenario where the intra-component edge helps to merge the two remaining components indirectly? No, because the intra-component edge is entirely within one initial component, so it doesn't provide connection between the two groups. Therefore, connectivity cannot be achieved. Hence intra-component edges cannot be part of a connecting set of exactly c-1 edges.
What about the possibility that some added inter-component edges become redundant because they connect components that are already indirectly connected via other added edges? In a tree, there are no cycles; but if you have a cycle, you'd have more than c-1 edges. However, with exactly c-1 edges, the subgraph induced by the added edges (considering initial components as nodes) must be acyclic. If it had a cycle, then number of edges >= number of nodes in that subgraph, leading to at least as many edges as nodes; but with exactly c-1 edges on c nodes, it must be a tree (connected and acyclic). So it cannot contain cycles.
Thus the set must be a tree on the component graph, and all edges are inter-component. So our counting is correct.
Now, we must ensure that we are counting sets of edges that are not already present. Since all inter-component edges are missing initially (by definition of components), we don't have to worry about some of those edges already existing (they don't). So it's fine.
Thus the problem reduces to a straightforward computation after finding component sizes.
But is it really that simple? The problem is from Codeforces? Possibly there is a catch: The graph might have multiple edges? No, "No more than one direct link can exist between two clues." So simple.
Also, note that T is defined as the minimum number of additional direct links needed. That might be computed as (number of components - 1) indeed. But could there be a case where the graph is not connected but the minimum number of additional edges needed is something else because there might be isolated vertices that need to be connected, but what about if the graph has some components but there are no missing edges between some components? Actually, there are always missing edges between components because there are no edges. So minimum is always c-1.
Thus we can safely compute T = c-1.
Now the answer formula is (product of component sizes) * n^{c-2}. However, we need to be careful about the modulo: Since k can be up to 1e9, but we are doing multiplication modulo k. However, note that if k is not prime, we cannot use modular inverse, but we don't need it.
But wait, the exponent c-2 could be negative when c=1? We handle that separately.
Now, we must also consider the possibility that n^{c-2} might be computed modulo k, but if k is not prime and we do exponentiation, that's fine.
Now, check large n: n=1e5, c could be up to 1e5 (if no edges). Then product of sizes = 1 * 1 * ... * 1 = 1. So answer = 1 * n^{c-2} mod k = n^{c-2} mod k. n^{c-2} could be huge; exponent ~1e5, but we can compute fast exponentiation in O(log(c-2)) = O(log n). That's fine.
But if c is large and sizes are not all 1, product of sizes may overflow if we compute as long long without modulo? We'll compute modulo k after each multiplication. However, note that k may be as small as 1, then everything is 0 modulo 1. But we need to handle mod 1 properly.
Now, we must ensure that we correctly compute component sizes. Using DSU: we union edges, then we can count sizes by iterating from 1 to n, find root, increment count. Since n up to 1e5, DSU with path compression and union by size works.
But careful: The graph may have multiple components, but there might be isolated vertices that have no edges; they are components of size 1.
Now, compute product mod k: We'll initialize prod = 1 % k. For each component size s_i, prod = (prod * (s_i % k)) % k. But note: if k=1, we can directly return 0. But we can also compute modulo 1 yields 0 always. So we can early return 0 if k == 1? Actually, answer modulo 1 is always 0. But check the problem: k >= 1, and we need to print modulo k. So if k=1, answer = 0. However, sample output for first sample with k=1e9 is 1. So we need to handle k=1 as 0. That's fine.
Now, implement:
Read n,m,k.
If k == 1: print 0 and return.
Initialize DSU of size n.
Loop m times: read a,b; union(a-1,b-1).
After unions, compute sizes: use an array root_count of size n initialized to 0. For i from 0 to n-1: root = find(i); root_count[root]++.
Collect sizes: for each root where root_count>0, push to vector.
Let c = vector size.
If c == 1: print 1 % k (but since k>1? if k==1 we already returned, but for safety: print 1 % k = 1 if k>1 else 0, but we already handled k=1 separately. So print 1.
Else:
prod = 1
for each s in sizes: prod = (prod * (s % k)) % k
exp = n^(c-2) mod k. Use fast exponentiation modulo k.
ans = (prod * exp) % k
print ans.
But wait: There is another nuance: The product of sizes might be computed modulo k, but the exponent n^{c-2} also mod k. Multiplication yields ans mod k. That's fine.
But is there any case where the product might be zero modulo k even if k not prime? For instance, if k=6 and one of sizes is 2 and another is 3, product=6 => 0 mod 6. That's acceptable.
Now, test with sample: sample 3: n=4, m=1, edge (1,4). sizes: [2,1,1], prod=2, exp = 4^{1} =4, ans=8.
Now consider n=1. n=1, m=0. Then c=1, T=0, answer=1. Our code: if c==1 print 1. Works.
Now consider n=1, m=0, k=1: we return 0. But is that correct? The answer modulo 1 is 0. So fine.
Now, is there any hidden twist? The problem statement: "Sherlock Holmes counted the minimum number of additional direct links that he needs to find to solve the crime. As it turns out, it equals T." Could it be that T is given in the input? No, it's not given. So we compute T ourselves. But the problem may intend that T is computed from the graph. So that's fine.
Now, verify more complex scenario: Suppose the initial graph has multiple components, but some component may have multiple vertices, product sizes may be large. That's okay.
Now, I recall a known Codeforces problem: "Sherlock and his girlfriend" no. Actually, I think it's from CF round: "C. Sherlock's array" no. I've seen a problem "B. Sherlock and his girlfriend" but not this. Another: "Sherlock and the Counting" maybe. This problem seems too trivial for a contest? Possibly they intend to have a more complex combinatorial answer, but perhaps there is a nuance: The minimum number of additional direct links equals T, but T is not necessarily c-1? Wait, the problem says: "Sherlock Holmes counted the minimum number of additional direct links that he needs to find to solve the crime. As it turns out, it equals T." So T is determined from the graph. And then we need to count the number of different ways to find exactly T direct links so that the crime is solved. This is exactly what we did.
But maybe there is a catch: Could there be a case where the graph initially has multiple components but some of them are already connected indirectly? No.
Wait, maybe the phrase "Sherlock Holmes counted the minimum number of additional direct links that he needs to find to solve the crime." Could be interpreted as: He knows that T is the minimum number needed, but we (the solver) are not given T; we have to compute T? No, we compute from graph. That is consistent.
Another nuance: The direct links are mutual, so undirected.
Now, is there any possibility that the graph already contains some edges that are not part of any component? That doesn't make sense.
Alright.
However, I suspect that the problem might have originally been more complicated: maybe T is not necessarily c-1, because the graph may have multiple edges? Or maybe the condition for "linked" is transitive? But it's defined clearly: A and B are considered linked if there is a path between them. So connectivity.
Thus it's indeed about connecting components.
Now, check if any constraints force a more complicated solution: n up to 1e5, m up to 1e5, so reading edges and DSU is fine.
Thus solution seems straightforward.
But before finalizing, let's think about potential pitfalls: The product of sizes could be large but we compute modulo k. However, if k is not prime and we multiply many numbers, we must use modulo, but the product may be zero modulo k. That's fine.
But there is one more subtlety: The answer formula (∏ s_i) * n^{c-2} is derived assuming that we consider all trees on the component graph. But is it possible that some of those trees produce the same set of edges? No, trees are distinct sets of edges between components. For a given tree, the realizations produce distinct sets of edges because each edge is specified by its endpoint vertices. If two different trees produce the same set of edges, that would be impossible because the set of edges determines which components are connected: the edges themselves are inter-component, and the pattern of which components are connected is the tree. Could two different trees produce the same set of actual edges? For that to happen, the set of edges would have to correspond to two different trees on the component graph, which is impossible because the set of edges itself defines a graph on the components. If that graph is a tree, it's unique as a graph (the tree). So no double counting.
Thus answer is correct.
Now, let's test with some random small cases via brute force to ensure formula matches.
We'll test n=3, all possible initial graphs, but we have to compute T as minimum edges needed. We'll write a small brute enumerator for n up to maybe 5, for random m, compute answer via brute force: generate all subsets of missing edges of size T, check connectivity, count. Compare with formula.
But since we are reasoning, we can test a few.
Case: n=4, no edges (m=0). Then c=4, sizes [1,1,1,1]. Product=1, n^{2}=16, answer=16. Let's brute: Need to add exactly T = 3 edges to make graph connected. Number of ways to choose 3 edges among all missing edges (which are all 6 possible edges) such that the resulting graph is connected (and using exactly 3 edges). The number of labeled trees on 4 vertices is 4^{2}=16 (Cayley's formula). Indeed, the number of spanning trees on 4 labeled vertices is 4^{2}=16. And since there are no existing edges, each tree corresponds to a set of 3 edges that connects all vertices. And Cayley's formula gives 4^{2}=16. So matches.
Case: n=4, existing edges: one edge, say (1,2). Then components: {1,2} size2, and vertices 3,4 isolated sizes 1,1. c=3, sizes [2,1,1]. answer=24=8. Let's brute: Missing edges: total possible edges =6, existing 1, missing 5. T=2. Need to pick 2 edges among missing such that final graph connected. Enumerate: All pairs of missing edges (choose 2) from the set of 5 edges, count those that connect all. Could compute expected 8. Let's quickly enumerate: vertices 1,2 connected. Missing edges: (1,3),(1,4),(2,3),(2,4),(3,4). Need to pick 2 edges to connect the three components: component A={1,2}, B={3}, C={4}. Inter-component edges: A-B: (1,3),(2,3) (2 edges), A-C: (1,4),(2,4) (2 edges), B-C: (3,4) (1 edge). We need exactly two edges that connect all three. That's exactly our tree count: trees: (A-B, A-C): 22=4, (A-B, B-C): 21=2, (A-C, B-C): 21=2, total 8. Yes.
Case: n=5, existing edges: (1,2),(2,3) -> component size3, others isolated 4,5. So sizes: [3,1,1]. c=3, product=3, n^{1}=5, answer=15. Let's brute: inter-component edges between A(size3) and B(size1): 3 edges (A-B) (i.e., (1,4),(2,4),(3,4)). Actually B is vertex 4. Similarly A-C: 3 edges (to vertex5). B-C: 1 edge (4,5). Trees: (A-B, A-C): 33=9, (A-B, B-C):31=3, (A-C, B-C):3*1=3 -> total 15. Yes.
Thus formula holds.
Now, consider case with two components of sizes >1. n=6, components: sizes [2,2,2] (c=3). product=8, n^{1}=6, answer=48. Check via tree enumeration: Trees on 3 nodes: three trees. For tree with edges (1-2,1-3): product = (s1s2)(s1s3) = (22)(22)=44=16. Similarly other two trees: each gives 44=16? Wait careful: For tree (1-2,2-3): (s1s2)(s2s3)=44=16. (1-3,2-3): also 4*4=16. Sum=48. Yes.
Now, more complex: n=5, components: sizes [2,3] (c=2). answer = s1s2 = 6. Indeed we need exactly 1 edge to connect them, any of the 23=6 edges works.
All good.
Now, we must ensure that when c=2, the formula gives product * n^{0} = product, correct.
Now, also consider that there might be edges already present that cause components to be more than one. But we already accounted.
Thus the problem is solved.
But wait, there is a nuance: The problem states: "Sherlock Holmes counted the minimum number of additional direct links that he needs to find to solve the crime. As it turns out, it equals T." That is given. But we are not given T; we infer it. That's fine.
Now, we should also consider if there could be isolated vertices that are not reachable? Already.
Now, code: Use DSU.
But careful: The graph may have up to 1e5 edges, DSU with path compression and union by size/rank is O(alpha(n)).
Now, compute component sizes: we can use an array size[root] after union. In DSU, we can maintain the size of each set as we union. After all unions, we can iterate over vertices, find root, and increment count for that root. Or we can directly use the DSU size array, but we need to collect sizes for each distinct root. After unions, we can traverse i from 0 to n-1, if parent[i] == i (root), then size[i] is the size of that component (if we maintained size). But careful: If we use path compression, the parent of some nodes may not be root? We can maintain an array sz that is only correct for roots. When we union, we update sz[root] accordingly. After all unions, we can iterate over all i, if find(i) == i (i is root after find with compression), then sz[i] is correct. But if we didn't call find on all, we can just do a loop: for i in 0..n-1: root = find(i); then we can count via a map or array. Or we can maintain an array that we fill after all find calls.
Simplest: after all unions, for i in 0..n-1: root = find(i); count[root]++. Then collect counts.
Now, product modulo k: we need to multiply each component size modulo k. But sizes up to 1e5, product may be large. But we compute modulo k.
Now, compute pow_mod(n, c-2, k). Use fast exponentiation.
Now, handle c=1: ans = 1 % k.
Now, special case: if k == 1, output 0 directly (since everything mod 1 is 0). Actually, we can also just compute modulo and it will be 0 anyway if we take modulo at each step. But product may become 0 if we multiply by something that is 0 mod 1? But modulo 1 of any integer is 0. So (prod % 1) = 0, pow_mod(...,1)=0? Actually, any integer % 1 = 0. So we can just compute normally, but pow_mod function must handle modulo 1 correctly: if k==1, then any result mod 1 is 0, so we can return 0. But if we implement pow_mod with while loop and modulo operation, x % 1 is 0, causing maybe division by zero? No, modulo operation with 1 is fine; 0%1=0, etc. However, when we compute a % mod in pow_mod, if mod==1, then the result will always be 0. So pow_mod(n, exp, 1) will return 0 for any positive exponent? Actually, if mod==1, then a % 1 = 0, then base becomes 0, and any multiplication yields 0, result = 0. But what if exponent = 0? pow_mod(n,0,1) should return 1 mod 1 = 0. So indeed it returns 0. So product* pow_mod %1 = 0. So we can just compute normally and output ans (which will be 0). But careful: product computed as (prod * s) % 1, each step yields 0 because mod 1 yields 0. So product becomes 0. Then ans = 0 * something = 0. So we can just compute without early return. However, if we compute product by starting with 1%1 = 0? 1 % 1 = 0. So product becomes 0. Then ans=0. That's fine. So we don't need early return. But we must ensure that in pow_mod we handle exponent=0 correctly: it should return 1 % mod. If mod=1, 1%1=0, so returns 0. That's fine. So we can just let the code run. However, one potential issue: If we compute product by multiplying modulo k and k=1, the product will be 0, and that's correct. So we can skip special case.
But we need to be cautious about integer overflow? We'll use long long for intermediate multiplication and modulo.
Now, DSU implementation: We'll use vector parent, rank/size.
Simpler: parent[i] = i; sz[i]=1 initially.
Union: find roots, if same, skip; else attach smaller to larger, update sz[larger] += sz[smaller].
After all unions, we need to collect sizes of components. But note that after path compression, some roots may have children with outdated sz? Actually, sz array is only maintained for roots. After unions, we may have done path compression on finds during unions; but we haven't called find on all vertices after unions. The sz array for non-roots is not meaningful. So we should either loop and do find(i) to get root, then use a separate count array, or we can use the sz array for roots by identifying roots: a node i is a root if parent[i]==i (but after path compression, some nodes may have parent changed; but we might have not compressed all; still, after all unions, the roots are those with parent[i]==i or after find). To be safe, we can do a loop: for i in 0..n-1: root = find(i); then increment cnt[root] (maybe using a map or array). But then we have to collect cnt values. That is fine O(n alpha). That yields component sizes. However, we can also just look at sz[i] for those i where parent[i]==i after we have done no further compression; but if we have used find with path compression during unions, some nodes may have been compressed, but the root's parent is itself; so we can simply iterate and if parent[i]==i then sz[i] is the component size (assuming we always kept sz updated only for root). But careful: During unions, we might have attached root of smaller to root of larger; we updated sz of the new root. The old root's parent is set to new root, but we did not reset its sz to 0. So if we later iterate and see parent[old_root] != itself, we skip it. So we can just collect sz[i] where i is a root (parent[i]==i). That gives component sizes directly. However, we must ensure that we have called find with path compression on all nodes? Not necessary; as long as we check parent[i] == i, it will be true only for roots. But after unions, some nodes might have parent pointing to a non-root if we didn't compress? Actually, in DSU with union by size and no path compression except during finds, the parent array may still form trees. If we haven't called find on many nodes, the root of a component might have parent[root] = root, yes. The other nodes have parent[child] = something, not root. So checking parent[i]==i works to identify roots. But we must be sure that we haven't changed parent of a root to something else without updating? No, only union operation changes parent of a root to another root. So after all unions, each component has exactly one node with parent[i]==i (the ultimate root). So we can collect sz[i] for those i. That is efficient. But we must ensure that we use path compression during union's find operations to keep the tree flat? Not necessary for correctness. But we may want to use find with path compression to avoid deep trees for later loops if we need to call find on each node. But here we don't need to call find on each; we just need roots. So it's fine.
Thus after unions, we can compute vector sizes; for i in 0..n-1: if parent[i]==i: sizes.push_back(sz[i]).
But note: If we used union-by-size, sz[i] for root i is the size of that component. Yes.
Now, we must be careful: In union operation, we need find(x) and find(y). We'll implement find with path compression to keep tree flat. That is fine.
Now, after unions, we have sizes.
Now, compute answer.
Edge Cases:
n=1, m=0 => components=1, answer=1.
n=1, m cannot be >0 because edges must be distinct and a≠b, so m=0. So answer=1.
n large, no edges => sizes all 1, c=n. product=1. answer = n^{n-2} mod k. That could be computed.
But note: n^{c-2} where c=n, exponent is n-2 which can be up to 1e5-2, which is fine.
Now, we need to compute pow_mod(n, c-2, k). However, n may be up to 1e5, and k up to 1e9, we can compute using fast exponentiation O(log(c-2)).
But note: c can be as large as 1e5, so exponent up to 1e5. log2(1e5) ~ 17, so fast exponent is fine.
Now, one more nuance: The formula (∏ s_i) * n^{c-2} holds for integer arithmetic, but modulo k we have to compute it. However, there might be issues with overflow when computing n^{c-2} if we use standard pow and mod, but we will use exponentiation with mod.
Now, is there any scenario where the product of sizes is 0 modulo k? That's fine.
Thus solution is trivial.
But given the problem statement, maybe they expected a more complex reasoning? Or maybe I've missed something: Could there be a scenario where the minimum additional links T is not c-1? Consider if the graph already has some "redundant" edges? But minimum number of edges to add to make a graph connected is indeed (number of components - 1) for any undirected graph. Because you can always take one vertex from each component and connect them in a chain. So it's minimal. There's no twist. So T = c-1.
Thus answer as above.
But wait, the problem statement says: "Sherlock Holmes counted the minimum number of additional direct links that he needs to find to solve the crime. As it turns out, it equals T." That might imply that T is known to us? But it's not given, we compute from graph. Perhaps there is a twist: The graph may have multiple connected components, but maybe some components are already "linked" through some indirect connections? No.
Alright.
Now, before finalizing, I'd like to consider if there is any alternative interpretation: "Sherlock Holmes counted the minimum number of additional direct links that he needs to find to solve the crime. As it turns out, it equals T." Could it be that T is given as part of the input? But the input format only shows n, m, k. So no T.
Now, a more complex test: n=6, m=2, edges: (1,2),(3,4). So components: {1,2} size2, {3,4} size2, {5} size1, {6} size1 => c=4, sizes [2,2,1,1]. product=4, n^{2}=36, ans=144. Let's quickly brute mental? Possibly correct. We can compute via enumeration: Inter-component edges: between A(size2) and B(size2): 4 edges, A-C:2, A-D:2, B-C:2, B-D:2, C-D:1. Need to select exactly 3 edges that connect all 4 components. The number of trees on 4 labeled nodes weighted: sum over trees product. According to formula: product sizes * n^{c-2} = (2211) * 6^{2}=436=144. That seems plausible.
Now, could there be any case where the existing graph has multiple edges within a component, but that doesn't affect sizes.
Thus I'm confident.
But let's double-check the derivation using known results. The number of ways to add c-1 edges to connect components of sizes s_i is (∏ s_i) * (∑ s_i)^{c-2}. Yes.
Now, one more check: Is it possible that some of the T edges we add are already present? But T edges are additional, so they must be from missing edges. Since inter-component edges are all missing, it's fine.
But what if there are multiple components and some of them have no missing edges? Actually, all inter-component edges are missing, so we can choose any.
Now, we should also consider if the graph might have loops? No.
Now, we also need to consider if there are multiple edges between the same pair of vertices? Not allowed.
Now, implementation details:
We'll read n,m,k.
We'll create DSU.
After unions, compute sizes as described.
If number of components == 1: answer = 1 % k.
Else:
prod = 1 % k;
for each size: prod = (prod * (size % k)) % k;
exp = pow_mod(n, c-2, k);
ans = (prod * exp) % k;
print ans.
But careful: size % k: size may be up to 1e5, k up to 1e9, so it's fine.
Potential integer overflow: When multiplying two numbers mod k, we can use (a * b) % k, but a and b up to k-1, product up to (1e9-1)^2 ≈ 1e18, which fits in 64-bit (max ~9.22e18). So we can use long long.
We'll use long long for all mod calculations.
But note: n can be up to 1e5, but we will use n mod k for exponentiation. Actually, n may be larger than k? n <= 1e5, k up to 1e9, so n < k possibly but not necessarily; k could be smaller than n (e.g., k=7, n=10). So we should take n % k for exponentiation. However, in the formula we have n^{c-2}, but n is the total number of vertices, not modulo something. The product (∏ s_i) * n^{c-2} is an integer. We compute it modulo k. So we need to compute (n mod k)^{c-2} mod k. But careful: If k is not prime, exponentiation mod k works fine. But is it valid to reduce n mod k? Yes, because we are computing modulo k, and exponentiation is in the ring of integers modulo k, we can reduce base modulo k. However, is there any nuance if k is not coprime to n? That doesn't matter; modular exponentiation works for any modulus. So we can do base = n % k.
But wait: The formula (∏ s_i) * n^{c-2} is an integer product. To compute it modulo k, we compute (∏ s_i mod k) * (n^{c-2} mod k) mod k. This is correct because modulo multiplication distributes. So we can compute n^{c-2} mod k using base = n % k. Yes.
Now, we must be careful that n may be large (1e5) but k may be 1, but we handled.
Now, test with sample: n=4, k=1e9, n%k=4, compute 4^{1}=4, fine.
Now, test with k smaller: n=10, c=5, product something, compute 10^{3} mod 7 = 1000 mod 7 = 6? Actually 10 mod 7 =3, 3^3=27 mod7=6. So that's fine.
Now, we also need to compute product of sizes modulo k, but sizes themselves we should also mod k.
Now, consider the case where k is not prime, and product may become 0 mod k, that's fine.
Now, memory: DSU arrays of size n+1.
Now, let's think about time: O(n+m) alpha.
Now, implement.
But wait, the problem might have a twist: The number of ways to add exactly T edges might include the possibility of adding edges that are not necessarily all between different components, but still yield connectivity with exactly T edges because the initial graph might have some edges that are not part of any component? That's impossible. Or because the definition of "linked" is not necessarily connectivity in graph theory? It says: "Clues A and B are considered linked either if there is a direct link between them or if there is a direct link between A and some other clue C which is linked to B." That's exactly connectivity.
Thus fine.
Given that the problem seems too easy, perhaps I've missed a nuance: The phrase "Sherlock Holmes counted the minimum number of additional direct links that he needs to find to solve the crime. As it turns out, it equals T." Could it be that T is not necessarily equal to the number of components minus one because the graph might already have some edges that are not used? But no.
Wait, maybe the graph might have multiple edges between the same pair? Not allowed.
Alternatively, maybe the detective can "find" direct links that are already present? That would be redundant and not counted as additional? The problem says "additional direct links". So we only consider adding edges that are not already present.
Now, I recall a known Codeforces problem: "Sherlock and the Counting" maybe it's problem "C. Sherlock and his girlfriend"? No.
Search memory: There is a problem "B. Sherlock and his girlfriend" about primes. Another problem "A. Sherlock and his girlfriend"? Not.
Maybe this problem is from Codeforces Round #589 (Div. 2) "C. Primes and Multiplication"? No.
I recall a problem named "Sherlock and the Counting" from some contest, but not sure.
Anyway.
Given that the solution is so short, it's plausible as a problem in a contest, maybe as a medium difficulty but with this combinatorial insight. Many participants might think it's more complex. But still, it's simple after derivation.
However, there is one more nuance: The problem statement says: "Please count the number of different ways to find exactly T direct links between the clues so that the crime is solved in the end." It doesn't say that the T direct links must be additional beyond the existing ones? Actually, it says "to find exactly T direct links" which presumably means to find new links. But we assume they are distinct from existing links. The phrase "additional" in the earlier sentence suggests they are additional. So we count sets of edges not already present.
Now, we also need to ensure that the T edges we choose are distinct and unordered. Our counting via trees and product of s_i*s_j accounts for unordered edges because each tree edge is an unordered pair of components, and then we choose an unordered pair of vertices. That's fine.
Now, we should also check for the possibility that the graph already has some edges, and T might be 0 but the graph might not be connected? That cannot happen because if it's not connected, minimum additional edges >0, so T>0. So T=0 only when graph connected.
Now, we should also consider if there might be multiple edges that are already present that cause the graph to be almost connected? No.
Now, a subtlety: Could there be a scenario where the initial graph has some vertices that are isolated (size 1 components) and also some components of size >1, and the product of sizes might be large but that's fine.
Now, also note that we must use modulo k, but the product of sizes may be computed modulo k. However, the exponent n^{c-2} mod k is computed. Since k can be up to 1e9, multiplication of two numbers up to k-1 yields up to 1e18, which fits in 64-bit. In C++, long long is enough.
But what if k is near 1e9 and we multiply two numbers near 1e9, product near 1e18, which is less than 9.22e18, so safe.
Now, let's think about potential pitfalls for c-2 exponent when c=2: exponent 0, pow_mod should return 1 % k. So we must implement pow_mod to handle exponent 0 correctly.
Now, for c=1 we handled separately.
Now, is there any scenario where c > 1 but n^{c-2} is huge and we compute pow_mod, but exponent may be up to 1e5, and we do O(log exponent) multiplications, each multiplication mod k. That's fine.
Now, we should also consider that n mod k may be 0, then n^{c-2} mod k = 0 for any positive exponent, and 1 if exponent 0. So answer becomes 0 (if c>2) or product (if c=2). That's fine.
Now, we should verify with a test: n=2, k=2, m=0 => c=2, product=1, n^{0}=1, ans=1 mod 2 =1. That's fine.
Now, consider n=3, m=0, k=2 => answer =3 mod 2 =1. But is that correct? Actually, there are 3 ways to add 2 edges to connect 3 vertices. 3 mod 2 =1. That's fine.
Now, implement.
But I'm still a bit uneasy because the problem seems too straightforward. Let's read the problem statement again carefully, maybe there is a twist: "Sherlock Holmes counted the minimum number of additional direct links that he needs to find to solve the crime. As it turns out, it equals T." Could it be that T is given as input? No, the input format is only n,m,k. So T is derived.
Perhaps there is another condition: "Please count the number of different ways to find exactly T direct links between the clues so that the crime is solved in the end." But maybe "solve the crime" means that each clue is linked to all other clues, i.e., the graph becomes a complete graph? That would be a different interpretation: "each clue to be linked to all other clues (maybe not directly, via some other clues)." That's just connectivity. So it's correct.
But what if "linked" means something else? The description: "Clues A and B are considered linked either if there is a direct link between them or if there is a direct link between A and some other clue C which is linked to B." That is the definition of connectivity in an undirected graph (the transitive closure). So yes.
Thus the condition for solving the crime is that the graph is connected.
Thus our interpretation stands.
Now, maybe there is another nuance: Sherlock can find direct links, but he might also "find" links that are already there? That seems nonsensical; he has already found some links; now he needs to find additional ones.
Thus our solution is correct.
I will write the solution accordingly.
But before finalizing, let's think about the possibility of the initial graph having multiple edges between the same component? Not.
Now, also, we should consider if there is any constraint that n is up to 10^5, so product of sizes could be extremely large, but we only need modulo.
Now, I'll produce a solution.
However, I recall a known result: The number of ways to make a graph connected by adding exactly c-1 edges is product of component sizes times n^{c-2}. I've seen this in Codeforces problem "Misha and Forest" or something? Actually, there is a problem "C. Connect" maybe.
But wait, the problem might be from Codeforces Round #69 (Div. 2) "B. Sherlock and his girlfriend"? No.
I think it's from Codeforces Round #101 (Div. 2) "C. Genealogy"? Not.
Anyway.
Let's test with some random cases using brute force for small n to be extra sure.
We'll write a quick mental or pseudo test.
n=5, random edges. For each possible initial graph, compute components, compute formula, and verify by brute enumerating all subsets of missing edges of size T that make graph connected.
We can do for n=5, consider all possible initial graphs? Too many, but we can test some.
Case 1: n=5, m=0: c=5, sizes all 1. Formula: 1 * 5^{3}=125. Brute: Number of spanning trees on 5 labeled vertices is 5^{3}=125 (Cayley). So correct.
Case 2: n=5, one edge (1,2). Then components: {1,2} size2, and vertices 3,4,5 isolated sizes 1 each => c=4, sizes [2,1,1,1] product=2, n^{2}=5^2=25, answer=50. Let's brute conceptually: Inter-component edges: between A(size2) and B(size1): 2 edges each (with vertices 3,4,5). So three singletons. So total inter-component edges: A-B_i: each 2 edges, B_i-B_j: each 1 edge (between singletons). So total possible inter edges count: 32 + C(3,2)1 = 6 + 3 = 9. Need to select exactly T = 3 edges to connect all 4 components. Count number of trees weighted: product sizes =2111=2, times n^{2}=25 gives 50. We can compute via enumeration: Trees on 4 nodes: there are 4^{2}=16 trees (Cayley). But those are for labeled nodes with no weights. However, here node A has weight 2 (i.e., each edge incident to A has 2 choices), other nodes weight 1. The weighted sum is 2 * (sum over trees of product of weights of edges? Actually each tree contributes product of s_i^{deg(i)}. We can compute: sum_{trees} 2^{deg_A}. Since deg_A is the degree of A in the tree. For trees on 4 nodes, degree distribution: possible degrees of A: 1,2,3. Number of trees with A having degree d: number of trees on 4 labeled nodes where a specific node has degree d. For Cayley, the number of trees on 4 labeled nodes is 16. The number of trees where a given node has degree d can be computed. For node A, degree 1: means A is leaf. Number of trees where a given vertex is leaf? For any tree on labeled n vertices, the number of trees where a given vertex has degree k is given by some formula. For n=4, we can list: total trees 16. For a fixed vertex, degree 1: count? Let's compute: Choose which neighbor A connects to: 3 choices. The remaining 3 vertices must form a tree (since the whole tree has 3 edges, after connecting A, we need a tree on the remaining 3 vertices (which has 2 edges). Number of trees on 3 labeled vertices is 3^{1}=3. However careful: When we connect A to a specific vertex, the rest of the tree (on vertices {B,C,D} excluding A) must be a tree that includes that neighbor? Actually, after fixing edge A-X, we need to complete the tree on all 4 vertices. This is equivalent to choosing a spanning tree on the complete graph of 4 vertices that includes edge A-X. The count of trees containing a specific edge (A-X) is: total trees * (number of edges in tree? Actually easier: number of trees where A is leaf means that A is connected to exactly one vertex. So choose its neighbor: 3 choices. For each such neighbor X, we need a spanning tree on the remaining 3 vertices (including X) that connects them, but the overall tree must have exactly 3 edges: one is A-X, and the other two must connect all four vertices without cycles. That is essentially a tree on the 4 vertices that includes edge A-X and where A has degree 1. This is equivalent to choosing a spanning tree on the 3 vertices other than A, and then attaching A to any one of those tree's vertices? Actually, if we take any tree on the 3 vertices {B,C,D} (which has 2 edges) and then add edge A-X where X is one of those 3 vertices, the resulting graph on 4 vertices has 3 edges and is connected? Let's test: Suppose we have a tree on {B,C,D} which is connected. Adding edge A-X where X is in {B,C,D} yields a connected graph with 3 edges, which is a tree (since it has 4 vertices and 3 edges). However, does this count each tree exactly once? If we take a tree on {B,C,D}, there are 3^{1}=3 trees (since Cayley: number of trees on 3 labeled vertices = 3). For each such tree, we can attach A to any of the 3 vertices. That yields 33=9 trees. But total trees on 4 vertices is 16, so that suggests 9 trees with A leaf? Possibly. However, if we attach A to a vertex that is already in the tree, the resulting tree might have A leaf, yes. So there are 9 trees where A is leaf. Let's verify by manual: For 4 labeled vertices, total trees 16. Number where a specific vertex is leaf: it's known that for a tree on n vertices, the expected degree of a vertex is 2*(n-1)/n = 2 - 2/n, so for n=4, average degree 1.5, so sum of degrees = 6, each vertex average 1.5. So number of trees where vertex has degree 1 is (average degree 1) maybe? Not directly. Let's compute using Prufer codes: For n=4, each tree corresponds to a Prufer sequence of length 2 over {1..4}. In Prufer, the degree of vertex i is 1 + number of times i appears in sequence. For vertex A (say 1), degree 1 means it appears 0 times in Prufer sequence. Number of sequences where 1 does not appear: each of the two positions can be any of {2,3,4}, so 3^2 = 9. So indeed 9 trees with degree 1 for vertex 1. So degree distribution: degree 1: 9 trees; degree 2: appears exactly once in Prufer: number of sequences where 1 appears exactly once: choose which position (2 choices) * that position is 1, the other position is from {2,3,4} (3 choices) => 6 trees; degree 3: appears twice: sequences (1,1): 1 tree. So 9+6+1=16.
Thus for our weighted sum: each tree contributes 2^{deg_A} (since only A has weight 2, others weight 1). Sum = 92^1 + 62^2 + 12^3 = 92 + 6*4 + 8 = 18+24+8=50. Yes matches.
So formula works.
Thus solution is correct.
Now, but there is one more nuance: The graph may have multiple components, and some components might have size 0? No.
Now, finalize.
But wait, re-reading problem statement: "Sherlock Holmes counted the minimum number of additional direct links that he needs to find to solve the crime. As it turns out, it equals T." Could it be that T is given as an input but in the problem statement it's not in the input format? The input format says "three space-separated integers n, m, k". No T. So T is derived.
But maybe the problem originally had T in input but they removed? Check examples: They only give n,m,k. So T is not input. So our interpretation is correct.
Thus we will implement as described.
Now, potential pitfalls: The product of component sizes may overflow even before modulo if we multiply all sizes without modulo, but we will do modulo at each step. However, we have to compute product modulo k, so we will reduce after each multiplication.
Now, one more nuance: The answer could be huge, but modulo k we output.
Now, consider if k is large, up to 1e9, but product may become 0 modulo k if k divides product. That's fine.
Now, testing with large n and no edges: n=100000, m=0, k=1000000000. Compute product=1, exp = n^{n-2} mod k. That's n^(n-2) mod k. We need to compute that efficiently. Since exponent ~1e5, fast pow O(log exponent) ~ 17 steps, okay. But note: exponent is huge (1e5) but number of multiplications is about 17 (since exponent binary length ~17). That's fine. However, we need to compute base = n % k. n=100000, k=1e9, base=100000. Then compute 100000^(99998) mod 1e9. That's feasible with fast exponentiation using exponentiation by squaring with O(log exponent) ~ 17 steps. Actually, log2(1e5) ~ 17, yes. So that's fine.
But wait: exponent is c-2, which could be up to 1e5, not 1e5 bits? Actually, exponent value is up to 1e5, which in binary is about 17 bits. So indeed O(log exponent) = O(log n) ~ 17 multiplications. So it's very fast.
Now, is there any scenario where c-2 is huge? c can be up to n=1e5, so exponent up to 99998, that's still only 17 bits. Actually, 99998 in binary is about 17 bits. So number of multiplications ~ 17. That's fine.
Wait, but exponent is an integer up to 1e5, which is 17 bits, yes.
Thus pow_mod is cheap.
Thus overall solution is O(n α(n) + log n). Good.
Now, we need to be careful with DSU and large input. Use fast I/O.
Now, let's write code.
But I'm still thinking: Is there any scenario where the graph might have self-loops? Input says a≠b, so no.
Now, confirm: The graph is undirected, so each edge appears once in input.
Now, one more nuance: The problem might require to count number of ways to find exactly T direct links, but they might consider the links unordered (i.e., the set of links). That's what we did.
Now, we should consider the possibility that the initial graph might have multiple components but also some edges that are not yet discovered? No.
Thus final answer.
I'll now produce the final solution.
But before that, let's double-check the derivation with an example where some component sizes are large: n=100, two components sizes 40 and 60, c=2. Answer = 40*60=2400. That is number of ways to add one edge between the two components. That's correct.
Now, consider three components sizes 30, 30, 40. c=3, answer = 303040 * 100^{1} = (36000)100 = 3,600,000. But is that correct? Let's compute manually: number of trees on 3 nodes: 3 trees. For tree connecting 1-2 and 2-3: product = (3030)(3040) = 900 * 1200 = 1,080,000. For 1-2 and 1-3: (3030)(3040) = same 1,080,000? Wait careful: (1-2) product = 3030=900, (1-3) product = 3040=1200, product = 1,080,000. For 1-3 and 2-3: (3040)(3040)=1200*1200=1,440,000. Sum = 1,080,000+1,080,000+1,440,000 = 3,600,000. Yes.
Thus formula works.
Now, ensure we take modulo after each multiplication.
Now, we also need to handle the case where k is 0? But k >= 1 according to constraints.
Thus finalize.
Now, let's think about potential integer overflow in DSU size: size up to n=1e5, fits in int.
Now, implementation in C++:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
vector parent, sz;
int find(int x) {
if (parent[x] != x) parent[x] = find(parent[x]);
return parent[x];
}
void unite(int a, int b) {
a = find(a); b = find(b);
if (a == b) return;
if (sz[a] < sz[b]) swap(a, b);
parent[b] = a;
sz[a] += sz[b];
}
ll pow_mod(ll base, ll exp, ll mod) {
ll res = 1 % mod;
base %= mod;
while (exp > 0) {
if (exp & 1) res = (res * base) % mod;
base = (base * base) % mod;
exp >>= 1;
}
return res;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
code
int n, m, k;
cin >> n >> m >> k;
parent.resize(n);
sz.resize(n, 1);
for (int i = 0; i < n; i++) parent[i] = i;
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
a--; b--;
unite(a, b);
}
// collect component sizes
vector<int> sizes;
for (int i = 0; i < n; i++) {
if (parent[i] == i) { // root
sizes.push_back(sz[i]);
}
}
int c = sizes.size();
if (c == 1) {
cout << 1 % k << "\n";
return 0;
}
ll prod = 1 % k;
for (int s : sizes) {
prod = (prod * (s % k)) % k;
}
ll exp_val = pow_mod(n, c-2, k);
ll ans = (prod * exp_val) % k;
cout << ans << "\n";
return 0;
}
But is it safe to use parent[i]==i to identify roots? After union operations with path compression, some non-root nodes may have parent[i] != i, and roots have parent[i]==i. However, we must ensure that we have called find on each node to compress paths? Actually, if we never called find on a node that is not root after union, its parent may be a non-root (some intermediate). For example, we union a and b: we called find(a) and find(b) which returned roots. Then we set parent[small] = large. Now, after many unions, the tree may have depth >1. If we later do another union that involves a node that is not root, we call find which compresses path for that node, but we might not have called find on all nodes. At the end, some nodes may still have parent pointing to a non-root. However, the condition parent[i]==i only holds for the ultimate root of its component. For any other node, parent[i] will be some other node, but that other node might not be the root? Actually, in DSU without extra path compression, after unions, each component is a tree where only the root has parent[root]==root. For any other node, its parent is another node, but that parent might not be the root if the tree has depth >1. However, eventually by following the parent chain, you reach the root. The condition parent[i]==i will be false for all non-root nodes. So collecting sizes by checking parent[i]==i will correctly identify all roots. But we need to ensure that the size stored in sz[i] for a root is the total size of that component. When we performed union, we updated sz for the new root. For the old root, we set its parent to new root, but we did not reset its sz. So if we later iterate and see parent[old_root] != i, we skip it. So only the final root will have parent[i]==i and its sz is correct. So collecting sizes as described is correct.
But there is a nuance: If we use path compression during find operations, we might have flattened the tree, so many nodes' parent become root directly. In that case, parent[i]==i still only true for root. So it's fine.
Thus this approach works.
But we need to be careful: If we never call find on some node, it might have parent[i] = some node that is not root. But that node's parent[i] != i, so it's not considered root. So only roots are counted. Good.
Thus the sizes vector will contain correct sizes.
But there is a subtlety: In the loop for sizes, we use if (parent[i]==i) sizes.push_back(sz[i]); But after unions, some nodes may have been unioned and their size updated only for the root. For non-roots, sz[i] may still hold the size of the subtree originally? In typical DSU, we only maintain sz for roots. When we set parent[b] = a, we do sz[a] += sz[b]; but we do not zero out sz[b]. So sz[b] still holds its old size. If later we check parent[b]==b? No, because parent[b] is now a (or a root after compression), so condition fails, so we don't use sz[b]. So only roots are considered, and their sz is correct. So good.
Now, we should also consider the case where we use union by size but we also do path compression in find. That's fine.
Sample 3:
4 1 1000000000 edge 1 4 => after union: vertices 0 and 3 merged. sizes: root for {0,3} has sz=2, other two roots each sz=1. So sizes = [2,1,1] (order may vary). prod=2, exp=4^{1}=4, ans=8.
All good.
Now, let's also test with a case where k=1. For example, n=2,m=0,k=1 -> output should be 0. Our code: c=2, prod = 1%1=0? Wait: 1%1 = 0, so prod=0. Then exp = pow_mod(2,0,1) = 1%1=0? Actually pow_mod: we compute res = 1%1 = 0; base = 2%1=0; while loop: exp=0, loop not entered, returns res=0. So ans = 0*0%1=0. Output 0. So correct.
Now, test with n=1,m=0,k=1: c=1, we output 1%1=0. Output 0. That is correct? Should be 1 mod 1 = 0. Yes modulo 1, answer is 0.
Now, we need to ensure that when c=1, we output 1%k, not 1. In case k=1, it's 0. So that's fine.
Thus final solution.
But wait, there is a nuance: In the problem, it says "Sherlock Holmes counted the minimum number of additional direct links that he needs to find to solve the crime. As it turns out, it equals T." Possibly T could be 0 even if the graph is not connected? No, that would contradict the definition of minimum number.
Thus okay.
I think the solution is ready.
But there is another possible interpretation: Maybe the T is not equal to c-1, but rather the minimum number of edges needed to add to make the graph "linked" meaning that every pair of vertices is connected by a path of length at most something? No.
Given the examples match, it's fine.
Now, I'll write a final solution in C++.
But before finalizing, consider if there is any trick with large n and k being not prime and product being huge; our modular multiplication (a * b) % k is okay.
Now, note: When computing prod = (prod * (s % k)) % k, we need to ensure s % k is computed correctly. s may be up to 1e5, k up to 1e9, fine.
Now, I'd like to double-check the formula for the case when there are multiple components and some components are isolated but the graph might have multiple edges? Already covered.
Now, we can further simplify: The product of sizes and n^{c-2} can be computed directly.
Now, confirm with more examples.
Example: n=5, m=2 edges: (1,2) and (3,4). components: sizes [2,2,1]. product=4, n^{2}=25, ans=100. Let's brute compute? Might be correct.
Now, the problem could be from Codeforces and might have a solution exactly like this. I've seen a problem "C. Sherlock and Counting" but not sure.
Now, let's think about the time complexity: DSU operations O((n+m) α(n)). Good.
Now, we should also consider that the input may have m up to 1e5, so reading edges fine.
Now, we need to output answer modulo k.
Now, there is a potential overflow in pow_mod if we use int for exponent; exponent is up to 1e5, fits in int. But use long long for safety.
Now, finalize.
But wait: Is there any scenario where the graph is not simple? It says "No more than one direct link can exist between two clues." So it's simple.
Now, we also need to consider that the graph may have loops? a≠b ensures no loops.
Thus everything is consistent.
Now, I'm going to produce final answer.
However, I'm not fully convinced because many problems on Codeforces that look like this often have a twist like counting number of ways to add edges to make the graph connected, but they sometimes include the possibility that the graph might already have some edges within components that could be used to create cycles, but our T is minimum and we need exactly T edges; that forces a tree.
But what if the initial graph has some edges that are not part of any component? That doesn't make sense.
Thus solution stands.
Now, maybe there is another subtlety: The number of ways to find exactly T direct links includes the possibility of adding edges that were already present? No, because they are additional. The problem statement: "Sherlock Holmes counted the minimum number of additional direct links that he needs to find to solve the crime." So the links he will find are additional. So they must be among the missing edges.
Thus our counting of inter-component edges (all missing) is correct.
Now, I'll implement.
But wait: Could there be a case where the initial graph has some inter-component edges? That would mean that those two vertices are in the same component, contradicting component definition. So no.
Thus final.
Now, before final output, consider that the product of sizes may be computed modulo k, but the exponent n^{c-2} is mod k. If k is not prime, that's fine.
But hold on: I recall a known result: The number of ways to add k edges to make a graph connected, given component sizes, is something like ... Actually, there is a known formula for the number of ways to add edges to make a graph connected, but it's more complex if you add more than the minimum. But here it's exactly the minimum.
Thus final.
Now, I will also think about potential overflow in multiplication in pow_mod: base and res are up to k-1, product up to (k-1)^2, fits in 64-bit if k <= 1e9. So safe.
Now, confirm with extreme: k = 1e9, base = 1e9-1, res = 1e9-1, product ~ (1e9)^2 = 1e18 < 2^63-1 ≈ 9.22e18, safe.
Thus code.
Now, we should handle potential negative modulo? Not needed.
Now, final solution.
But before concluding, I want to test with a random case via mental enumeration for very small n to ensure no off-by-one.
n=2, m=0, c=2, sizes [1,1], product=1, n^{0}=1 => 1. ok.
n=2, m=1? That would be edge between the two vertices. But then m cannot be 1 because n=2, edge (1,2) would make graph connected. So T=0, answer=1. That's fine. Our code: after union, components: parent[0]==0? After union, both in same set, one root with size 2. So sizes = [2] only, c=1, answer 1%k. Works.
Now, n=3, m=1 edge (1,2). components: {1,2} size2, {3} size1 => c=2, product=2*1=2, n^{0}=1 => answer=2. Let's check manually: Need exactly 1 additional edge to connect the two components. The possible inter-component edges: between component A (size2) and B (size1) there are 2 edges ( (1,3) and (2,3) ). So 2 ways. Correct.
Now, n=4, m=2 edges: (1,2) and (3,4). components: sizes [2,2], c=2, product=4, answer=4. Indeed need 1 edge between the two components: 2*2=4 possibilities. Good.
Now, n=4, m=3 edges forming a tree? For example edges (1,2),(2,3),(3,4)? That's connected, c=1, answer=1.
Now, n=5, m=2 edges: (1,2) and (1,3). components: {1,2,3} size3, {4} size1, {5} size1, c=3, sizes [3,1,1], product=3, n^{1}=5 => answer=15. Let's brute: Inter edges: A-B: 3 edges to 4, A-C: 3 edges to 5, B-C: 1 edge between 4 and5. Trees: (A-B, A-C): 33=9, (A-B, B-C): 31=3, (A-C, B-C): 3*1=3 => total 15. Good.
Now, n=5, m=2 edges: (1,2) and (3,4). components: sizes [2,2,1], product=4, n^{2}=25 =>100. Already earlier we said 100. Check: Inter edges: A(size2)-B(size2): 4 edges, A-C: 2 edges, B-C:2 edges. Trees: (A-B,A-C): 42=8, (A-B,B-C):42=8, (A-C,B-C):22=4? Wait, careful: For tree (A-B, B-C): edges: A-B (4 options) and B-C (2 options) => 8; (A-C, B-C): A-C (2) * B-C (2)=4; (A-B, A-C): A-B (4) * A-C (2)=8; sum=20? That sums to 20, not 100. Something is off. Let's recompute: components: A: {1,2} size2, B:{3,4} size2, C:{5} size1. n=5. According to formula, answer = product sizes * n^{c-2} = (22*1) * 5^{1} = 4 * 5 = 20. Not 100. I mistakenly earlier said 100. Actually c=3, so n^{c-2}=5^{1}=5, product=4, total=20. Yes, that's correct. I earlier miscalculated exponent: c=3 => exponent=1, not 2. Because c-2 =1. So answer 20. So my earlier "100" was wrong. Let's recalc: c=3, n^{c-2}=5^{1}=5, product=4, answer=20. Let's brute check: We enumerated three trees and got 8+8+4=20. So correct. So earlier mistaken.
Thus careful: exponent is c-2, not n-2. So for c=3, exponent=1. So answer 20, not 100. Good.
Now, double-check for n=5, c=3, product=4, exponent=5 =>20. So formula correct.
Now, test for n=5, m=0: c=5, product=1, exponent=5^{3}=125 =>125. That's number of trees on 5 vertices. Yes.
Thus formula consistent.
Now, ensure that in the code we compute pow_mod(n, c-2, k) not n^{n-2}.
Now, final code.
But consider the possibility that we have to compute product of sizes and then multiply by n^{c-2}. However, what if c is very large (like 1e5) and n^{c-2} mod k can be computed quickly with binary exponentiation. That's fine.
Now, one more nuance: The product of sizes might be large, but we mod k. However, note that the formula (∏ s_i) * n^{c-2} is an integer. If we compute modulo k, we must ensure that we are not dividing by something; no division.
Thus final answer.
Now, I will write the solution in a clear manner.
But wait, there's an alternative: Use DSU to compute component counts and then direct formula. That's it.
Now, I'll produce final answer.
However, I'm going to double-check the problem statement from memory: It might be from Codeforces Round #415 (Div. 2) problem C? Actually, I recall a problem "Sherlock and his girlfriend" is about coloring. Not.
Search memory: There's a problem "C. Sherlock and the Counting" maybe not.
But there is a known problem: "Sherlock and the Valid String" no.
Given the simplicity, it's plausible that it's a problem from some contest.
Now, also note that the problem might require to compute T, but they gave T? The input doesn't have T. So we compute.
Maybe there is a twist: The minimum number of additional direct links might not be simply c-1 if the graph already has some edges that can be used to connect components indirectly? But the definition of components already accounts for all existing connections. So it's c-1.
Thus fine.
Now, finalize.
But wait, I recall a similar problem from Codeforces: "C. Little Pony and Summer Sun Celebration"? No.
Maybe it's from "C. Building a Fence"? No.
Alright.
Now, I'll write the code.
But also, I should consider potential overflow in multiplication of (prod * (s % k)) where s % k is computed as s % k, which yields an int. But if k is up to 1e9, and s up to 1e5, s % k = s (since s < k unless k <= s). But if k is small, say k=3, s=4, s%k=1. So product remains mod k. That's fine.
Now, also note that if any s_i % k == 0, then product becomes 0, and the whole answer becomes 0. That's fine.
Now, all good.
Now, before final, let's think about the scenario where c=2 but n is large; exponent 0, answer = product. That's correct.
Now, I'll implement.
But I'm still not fully satisfied: Could there be a scenario where the graph has some edges that are not within a component? That would merge components, so they are in same component. So no.
Thus final.
Now, I'll produce final answer.
I'll also add comments.
Potential bug: In DSU, we used vector parent, sz. But after unions, we might have path compression not applied to all nodes. The condition parent[i]==i to identify root is fine, but if we used path compression during union (we call find which compresses path for the arguments), some nodes may have been compressed. However, for nodes that were never visited by find after they became non-root, they may still point to a non-root. That's okay because they are not roots.
But what about the root's parent? It's itself.
Thus sizes collection works.
Now, verify: Suppose we have two unions: unite(0,1) => root0 size2, parent[1]=0. Then unite(2,3) similarly. Then we loop i=0..3. i=0: parent[0]==0 => sizes.push_back(sz[0]=2). i=1: parent[1]==0? after union, parent[1]=0, so false. i=2: root, size2. i=3: not root. So sizes = [2,2]. Good.
Now, if we had path compression during find, say we later called find(1) which would set parent[1]=0. That's already the case. So fine.
Now, test with more complex merging: unite(0,1), then unite(1,2). In second unite, find(1) returns 0 (root), find(2) returns 2, then we set parent[2]=0, sz[0]+=sz[2]. Now, parent[2]=0, parent[0]=0, parent[1]=0 (if path compressed maybe). Then loop: i=0 root, i=1 parent[1]==0? Actually if path compressed, parent[1]=0, so not root; i=2 parent[2]=0, not root. So sizes = [3] only. Good.
Thus works.
Now, final code.
But consider memory: parent and sz of size n, ok.
Now, any need for long long for sizes? Use int.
Now, ensure we use 0-index.
Now, final.
But wait, there is a nuance: The problem's input might have edges that are repeated? It says "It is guaranteed that any two clues are linked by no more than one direct link." So no duplicates.
Now, finalize.
Given the solution is short, I'll present it.
But is there any case where the answer might be computed incorrectly because we didn't consider that the graph might have isolated vertices that are considered components of size 1? That's fine.
Now, I'm going to produce final answer.
But I'm still thinking: Is it possible that the graph has multiple connected components but some of them are already connected via a path that goes through some intermediate vertices that are not directly linked? That's exactly what a component is: they are connected if there is a path. So they are in same component. So component count is exactly the number of connected components.
Thus T = c-1.
Now, final.
Now, I'll write the solution.
After writing, I'll test with some random small cases using a quick mental check:
n=5, random edges: suppose edges: (1,3), (2,4). Then components: {1,3} size2, {2,4} size2, {5} size1 => c=3, product=221=4, n=5, exponent=1 =>20. Let's manually compute possible ways: Need 2 edges to connect three components. Inter edges: A-B: 22=4 edges, A-C:21=2, B-C:21=2. Trees: (A-B,A-C):42=8, (A-B,B-C):42=8, (A-C,B-C):22=4 total 20. Yes.
Now, if there is an edge (1,2) and (2,3) and (4,5) => components: {1,2,3} size3, {4,5} size2 => c=2, product=6, answer=6 (edges between them: 3*2=6). Good.
Thus seems consistent.
Now, I think it's correct.
One more potential pitfall: The graph might have multiple components but also some isolated vertices, but the product of sizes includes those isolated vertices as size 1, which doesn't affect product. That's fine.
Now, answer mod k.
Now, I'll produce final solution.
But wait, there's a nuance: In the problem statement, they say "Sherlock Holmes counted the minimum number of additional direct links that he needs to find to solve the crime. As it turns out, it equals T." Could it be that T is not necessarily c-1 but something else because the graph might have articulation points? No.
Alright.
Now, I'll write final answer. ```cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
vector parent, compSize;
// DSU find with path compression
int find(int x) {
if (parent[x] != x)
parent[x] = find(parent[x]);
return parent[x];
}
// DSU union by size
void unite(int a, int b) {
a = find(a);
b = find(b);
if (a == b) return;
if (compSize[a] < compSize[b]) swap(a, b);
parent[b] = a;
compSize[a] += compSize[b];
}
// fast exponentiation modulo mod
ll pow_mod(ll base, ll exp, ll mod) {
ll res = 1 % mod;
base %= mod;
while (exp > 0) {
if (exp & 1) res = (res * base) % mod;
base = (base * base) % mod;
exp >>= 1;
}
return res;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
code
int n, m, k;
cin >> n >> m >> k;
// DSU initialization
parent.resize(n);
compSize.assign(n, 1);
for (int i = 0; i < n; i++) parent[i] = i;
// read existing edges
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
a--; b--;
unite(a, b);
}
// collect sizes of connected components
vector<int> sizes;
for (int i = 0; i < n; i++) {
if (parent[i] == i) { // i is a root
sizes.push_back(compSize[i]);
}
}
int compCnt = sizes.size();
if (compCnt == 1) {
// already connected, T = 0, only one way: add nothing
cout << 1 % k << "\n";
return 0;
}
// product of component sizes modulo k
ll prod = 1 % k;
for (int s : sizes) {
prod = (prod * (s % k)) % k;
}
// n^(compCnt-2) modulo k
ll powPart = pow_mod(n, compCnt - 2, k);
ll ans = (prod * powPart) % k;
cout << ans << "\n";
return 0;