We need to parse the problem: There's an acyclic directed graph with n vertices, m edges, possibly multiple edges. Sources: vertices with no incoming edges. Sinks: vertices with no outgoing edges. The number of sources equals number of sinks; let that number be k.
We number the sources in increasing order of vertex numbers: source_1, source_2, ..., source_k (the vertices that are sources, sorted by vertex id). Similarly, sinks are numbered 1..k in increasing order.
Now we consider all possible sets of k vertex-disjoint paths (non-intersecting at vertices) such that each path goes from some source to some sink, each sink is reached exactly once, and each source is used exactly once? The problem says: "selects a set of k paths from all sources to the sinks in such a way that no two paths intersect at the vertices. In this case, each sink has exactly one path going to it from exactly one source." So yes, it's a bijection between sources and sinks via vertex-disjoint paths.
Define: for a given set of k paths, let a_i be the index of the source whose path ends at sink i (since each sink gets exactly one path from some source). Then we consider inversions among the permutation a: for i<j, if a_i > a_j, that's an inversion. If the number of inversions is even, first wizard wins (gets +1 coin). Otherwise second wins (first gets -1 coin). So the winnings of the first player is (number of sets with even inversion count) - (number with odd inversion count). Since each set contributes +1 for even, -1 for odd.
We need to compute total winnings modulo prime p, but note p may be small? Actually p is up to 1e9+7, prime, but we need modulo p. However winnings can be negative; we output a non-negative residue modulo p.
We need to count the sum over all sets of k vertex-disjoint paths of (-1)^{inv(perm)}? Actually if we assign +1 for even inversion, -1 for odd inversion. That's exactly the sign = (-1)^{inv}. So total winnings = sum_{sets} sign(permutation defined by paths). This is like the sum over all possible vertex-disjoint path systems of the sign of the induced permutation.
We must compute this sum mod p.
This looks like a combinatorial expression reminiscent of determinant. Specifically, given a directed acyclic graph, the number of ways to connect sources to sinks via vertex-disjoint paths can be encoded by a matrix of path counts? Indeed, the Lindström–Gessel–Viennot lemma (LGV lemma) says that for a directed acyclic graph (DAG), the signed sum over families of non-intersecting paths from a set of sources A_i to sinks B_{\sigma(i)} (with permutation σ) equals the determinant of the matrix M where M_{ij} = number of paths from source i to sink j (if we consider vertex-disjointness). But careful: LGV lemma applies when the graph is acyclic and we consider vertex-disjoint paths. The lemma states:
For sources A_1,...,A_k and sinks B_1,...,B_k, the sum over all families of vertex-disjoint paths (each connecting A_i to B_{\sigma(i)} for a permutation σ) of the sign of σ multiplied by the product of the numbers of ways along each path (if edges have weights, but we consider simple paths? Actually the lemma counts weighted paths: for each path, weight is product of edge weights; for counting distinct sets of edge-sets, we can set all edge weights to 1). Then the signed sum over such families equals det( (P_{ij}) ) where P_{ij} is the total weight (e.g., number) of paths from A_i to B_j.
But crucially, this holds when we consider all path families where paths are vertex-disjoint (or edge-disjoint? It works for non-intersecting paths, i.e., no common vertices). And the sum is over all families of such paths, each family consists of exactly one path per source-sink pair, with distinct sinks (so a permutation). The sign is the sign of the permutation.
Therefore, the total winnings of the first player (which is exactly the signed sum with sign = (-1)^{inv} = sign(perm)) over all sets of vertex-disjoint path families is exactly the determinant of the matrix M, where M_{ij} = number of (all) directed paths from source i to sink j.
But we must ensure that the LGV lemma is applicable: The graph is acyclic, vertex-disjointness (no two paths share a vertex) is required. The lemma's sum is over families of paths that are pairwise non-intersecting. The lemma states:
Let G be a DAG, and let A_1,...,A_k and B_1,...,B_k be vertices. For any permutation σ, let N(σ) be the total weight (i.e., sum over families of paths (P_1,...,P_k) where P_i is a path from A_i to B_{σ(i)} and all paths are vertex-disjoint) of the product of path weights. Then sum_{σ} sign(σ) N(σ) = det( M ) where M_{ij} = total weight sum over all paths from A_i to B_j.
Thus indeed, if we set all edge weights = 1, then M_{ij} = number of directed paths from source i to sink j. And N(σ) = number of families of vertex-disjoint paths connecting sources to sinks according to permutation σ. Our total winnings is sum_{σ} sign(σ) * N(σ). That's exactly the determinant of M.
But wait, is that correct? The LGV lemma requires that the only intersections considered are those where paths intersect at vertices (or edges). It counts families where paths are pairwise vertex-disjoint (non-intersecting). Our problem says: "no two paths intersect at the vertices." That matches vertex-disjointness. Also, each sink has exactly one path from exactly one source, and implicitly each source is used exactly once? It says: "selects a set of k paths from all sources to the sinks in such a way that no two paths intersect at the vertices. In this case, each sink has exactly one path going to it from exactly one source." It doesn't explicitly say each source is used exactly once, but since there are k sources and k sinks and we have exactly k paths that are vertex-disjoint, it's natural that each source must be used exactly once; otherwise you could have a source not used? But then you'd have more sources? Actually there are exactly k sources. If you select k paths from all sources to sinks such that each sink gets exactly one path, then each sink is matched. The paths are from some source to a sink. Could there be a source that is not used? That would mean two paths start from same source? But since sources have no incoming edges and paths are vertex-disjoint, they can't share a source because that would be intersecting at the source vertex. So each path must start from distinct source. Since we have exactly k sources and k paths, each source is used exactly once. So indeed we have a bijection. So the permutation mapping sinks to sources is exactly the a_i (source index for sink i). So the signed sum is over families of vertex-disjoint paths. That matches LGV lemma.
Thus total winnings = det(M) modulo p, where M is a k x k matrix with entries = number of directed paths from source i to sink j in the DAG.
BUT there is a nuance: The LGV lemma sums over all families of paths that are pairwise vertex-disjoint. However, does the lemma count families where multiple paths could use the same edge? That's fine, but vertices are disjoint. The lemma also counts families where paths might be length 0? No, sources and sinks are distinct? Could a source also be a sink? In the problem, a vertex could be both source and sink. That would mean it has no incoming and no outgoing edges. If a vertex is both source and sink, it's both in sources list and sinks list. In that case, the path from that source to that sink could be a trivial path of length 0 (just the vertex). That is a valid path? Typically in path counting, we consider paths of length zero (single vertex) as a path from a vertex to itself. But does the LGV lemma allow zero-length paths? Usually the lemma assumes distinct vertices and paths of positive length? I think we can consider trivial paths as well; they are directed paths with no edges. But we need to consider if they are allowed in the problem: The set of paths are k paths, each from a source to a sink, with no vertex intersections. If a vertex is both source and sink, we could have a path consisting of just that vertex. That vertex would be used as both a source and a sink. Since it's the same vertex, can it be used by another path? It would intersect at that vertex, so it cannot. So if a vertex is both source and sink, the only way to have vertex-disjoint paths is that if we map that source to that sink (i.e., trivial path), then that vertex is used only by that path. That seems allowed. So we need to include zero-length paths in the count for M_{ij} if source i = sink j. Usually, in path counting in DAGs, we include the trivial path? But careful: In many LGV lemma formulations, paths are considered to have at least one edge? Actually the typical LGV lemma deals with points in a lattice and directed paths that go from one point to another strictly increasing coordinates, so zero-length path occurs only if start equals end, but then they might count it as a path? It depends. However, we can adapt: Since the graph is acyclic, we can count paths of any length including 0? Usually, for a DAG, we define a path as a sequence of vertices v0, v1, ..., vL with edges v_i -> v_{i+1}. L >= 0 yields length L edges. For L=0, it's just a single vertex, which is a trivial path. Does the problem allow a path with no edges? The problem says "set of k paths from all sources to the sinks". Typically a path may consist of a single vertex? It says "paths", but they didn't explicitly say they must contain edges. Usually, a path can be zero-length (just a vertex) if start equals end. In the context of vertex-disjointness, using a trivial path is okay. But we must check: In the first sample, n=4, m=2, edges: 1->3, 2->4. Sources: vertices with no incoming: 1 and 2 (since 3 has incoming from 1, 4 from 2). Sinks: vertices with no outgoing: 3 and 4 (since 1 has outgoing to 3, 2 to 4). So no vertex is both source and sink. So trivial paths not relevant.
In second sample, edges: 4->1, 3->2. Sources: vertices with no incoming: 2 and 3? Let's compute: incoming: 1 has incoming from 4, so not source; 2 has incoming from 3; 3 no incoming? 3 has outgoing to 2, but incoming? Edges: only given 4->1, 3->2. So 3 has no incoming? No edge into 3, so 3 is source. 4 has outgoing to 1, but incoming? No edge into 4, so 4 is source. So sources: 3 and 4? But vertex numbers: need sorted: sources are vertices 3 and 4 (since increasing). Sinks: vertices with no outgoing: 1 (has incoming from 4, outgoing? none) and 2 (outgoing? none). So sinks: 1,2. So again no overlap.
Third sample: 4 vertices, edges: 2->1,2->4,3->1,3->4. Sources: vertices with no incoming: 2 and 3? Let's see: 1 has incoming from 2 and 3; 4 incoming from 2,3; 2 no incoming; 3 no incoming. So sources: 2,3. Sinks: vertices with no outgoing: 1 and 4? 1 has outgoing? no; 4 has outgoing? no; so sinks:1,4. No overlap.
Fourth sample: n=6, edges: 1->4,1->5,1->6,2->6,3->6. Sources: vertices with no incoming: 1 (since no incoming? Actually check: 1 has incoming? not listed; 2 no incoming; 3 no incoming; 4,5,6 have incoming. So sources: 1,2,3. Sinks: vertices with no outgoing: 4,5,6? But 4 has no outgoing? Not listed; 5 no outgoing; 6 has outgoing? Not listed. So sinks:4,5,6. No overlap.
Fifth sample: n=5, m=2 edges: 5->1, 3->4. Sources: vertices with no incoming: which have no incoming? 2? Let's compute: vertex 1: incoming from 5, not source. 2: no incoming edges, so source. 3: no incoming edges? Edges: 3->4, so no incoming, source. 4: incoming from 3, not source. 5: incoming? No edges into 5? 5->1, so no incoming, source. So sources: 2,3,5 (sorted: 2,3,5). Sinks: vertices with no outgoing: 1? outgoing? none, sink. 2? outgoing? none? Actually vertex 2 has no outgoing edges, so sink. 4? no outgoing edges? It only has incoming from 3, so sink. Also vertex? 5 has outgoing to 1, not sink; 3 has outgoing to 4, not sink. So sinks: 1,2,4 (sorted:1,2,4). Note that vertex 2 is both source and sink? Actually vertex 2 appears in sources list (since it has no incoming) and also in sinks list (since it has no outgoing). So vertex 2 is both source and sink. So we have overlap. In the example they say: "there are three sources — the vertices with the numbers (2, 3, 5) and three sinks — the vertices with numbers (1, 2, 4)." So indeed 2 is both. In the set of paths they describe: "For a single set of paths are 2 inversions". They don't show the image but we can guess: The graph has edges: 5->1, 3->4. So paths: source 2 (vertex 2) is a sink also, so it's possible to have a trivial path from source 2 to sink 2 (just vertex 2). Source 3 to sink 4 via edge 3->4. Source 5 to sink 1 via edge 5->1. That gives 3 paths: trivial path for 2->2, 3->4, 5->1. Those paths are vertex-disjoint: vertex 2, 3,4,5,1 all distinct? Actually 2 is only used in trivial path; 3 and 4 used; 5 and 1 used; all distinct. That works. So indeed trivial paths are allowed.
Thus we must include zero-length paths when source equals sink. Therefore M_{ij} should count number of directed paths from source i vertex to sink j vertex, including possibly the trivial path if they are the same vertex.
Now, we also need to consider multiple edges: the graph can have multiple edges, which contribute to multiple distinct paths (since edges are distinct). So path count should count each distinct sequence of vertices/edges? Typically in path counting, if multiple edges exist, they create distinct paths if they use different edges. The problem says: "The two sets of non-intersecting paths are considered to be different, if and only if there is an edge, which lies at some path in one set and doesn't lie at any path of another set." That means each set of paths is defined by the set of edges used across all paths (since vertex-disjointness ensures edges belong to exactly one path). So two families are considered different if the multiset of edges used differs. So indeed each path is a sequence of edges, and multiple edges produce distinct paths. So M_{ij} = number of distinct directed paths (as sequences of edges) from source i to sink j. That's standard for LGV: weight of a path is product of edge weights; if multiple edges, each edge is a separate object, we can assign weight 1 to each edge and count.
Thus the answer is det(M) modulo p.
But we must be cautious: The LGV lemma as stated is valid for weighted DAGs, counting each family of vertex-disjoint paths with product of path weights, and summing over permutations. Here, each family contributes exactly sign(σ). The number of families for a given σ is the number of ways to choose vertex-disjoint paths consistent with σ. That's exactly N(σ). So total signed sum = det(M). So answer = det(M) mod p.
But there is a subtlety: The LGV lemma typically assumes that the only possible intersections that can cause cancellations are accounted for via the determinant expansion. It requires that the graph is acyclic, but does it require that sources/sinks are distinct? Possibly they could be same vertices? Usually they are distinct points, but if a source equals a sink, we need to be careful: In the lemma, we consider paths from A_i to B_j. If A_i = B_j, then there's a trivial path (zero length). However, if there are also nontrivial cycles? But graph is acyclic, so no cycles. So trivial path is allowed, but there may be nontrivial paths from A_i to B_j if A_i != B_j? Actually if A_i = B_j, any nontrivial path would require an edge leaving A_i and eventually returning? But graph is acyclic, so a path from A_i to itself of positive length would be a directed cycle, impossible. So only trivial path exists. So that's fine.
Also, note that the LGV lemma requires that the paths considered are pairwise vertex-disjoint. In counting M_{ij} (total number of paths from A_i to B_j), we consider all paths, including those that might intersect other sources or sinks? That doesn't matter for the lemma; it's just the matrix entry.
Thus, the problem reduces to: Given a DAG, identify the set of source vertices (no incoming) and sink vertices (no outgoing) that have equal count k. Number them in increasing order. Compute M where M[i][j] = number of directed paths from source_i to sink_j. Then compute determinant modulo p.
Constraints: n up to 600, m up to 1e5, p up to 1e9+7 (prime). k (number of sources/sinks) could be up to n (600). So matrix size up to 600. We need to compute determinant modulo a prime (maybe not small). However, p may be up to 1e9+7, which is large, but we can compute determinant modulo p using Gaussian elimination with modular arithmetic. But the entries M[i][j] could be huge (exponential in n). But we need them modulo p. Since we will compute determinant mod p, we can compute M[i][j] modulo p. However, note that the number of paths could be enormous, but we can compute them modulo p using DP on DAG, because the graph is acyclic. However, we need to compute number of paths from each source to each sink. There are up to k ≤ n sources, up to n sinks. That's up to 600*600 = 360k entries. For each source we can compute the number of paths to all vertices via DP (topological order). But number of paths can be huge, we only need modulo p, but p is prime up to 1e9+7, but the counts may exceed mod, we compute mod p.
But caution: The LGV lemma's determinant equality holds over integers, not modulo p? It holds as an integer identity. Since we need answer modulo p (which is prime), we can compute det(M) mod p by computing M entries modulo p and then determinant modulo p. However, is it valid to reduce modulo p before computing determinant? The determinant of an integer matrix modulo p is the determinant of the matrix modulo p, because det is a polynomial in the entries. So if we compute each M_{ij} modulo p, the determinant modulo p will be correct as long as we work modulo p. However, there might be an issue: The LGV lemma sum equals the integer determinant. If we compute M entries mod p and then determinant mod p, we get the integer determinant mod p. That's exactly what we want: total winnings mod p. So it's fine.
Thus solution steps:
- Parse input, build adjacency list for directed edges. Graph may have multiple edges, so we need to treat each edge as separate. But for counting paths, multiple edges from u to v contribute multiplicatively: number of paths from u to w that go through an edge u->v: if there are multiple edges, each gives a distinct path. So essentially we can treat each edge as weight 1, and the number of paths from u to w is the sum over v of (number of edges u->v) * (number of paths from v to w). So we can model the graph with multiplicities: we can have a count of edges from u to v (let's call c[u][v]) but m up to 1e5, n up to 600, so we can store adjacency list with possibly duplicate entries; but for DP, we need to sum contributions. Instead we can store a list of neighbors and for each neighbor, count how many edges. But since m large but n moderate, we can accumulate multiplicity.
Simpler: For each u, we can store a list of (v, count). But we need to process topological order.
- Identify sources and sinks.
- Compute indegree and outdegree for each vertex (counting edges with multiplicity? Actually indegree/outdegree for determining source/sink: A source is a vertex with no incoming edges. In a multigraph, indegree is number of incoming edges, if >0 then not source. Similarly sink if outdegree==0. The problem says "source is a vertex with no incoming edges", that means indegree zero (count of incoming edges zero). Similarly sink if outdegree zero. So we use total count of edges, not just distinct adjacency.
So compute indegree and outdegree using the edge list.
But careful: The graph may have multiple edges; indegree counts them. That's correct.
-
Let sources = list of vertices with indegree==0, sorted increasing. Let sinks = list of vertices with outdegree==0, sorted increasing. They must have same length k; input guarantees that.
-
Compute M: a k x k matrix, where M[i][j] = number of directed paths (including trivial if source_i == sink_j) from source_i to sink_j modulo p.
Since the graph is acyclic, we can compute number of paths from each vertex to each sink via DP in reverse topological order.
We can process vertices in topological order (any linearization). Since we have DAG, we can compute topological sort. Then for each source (or for each vertex), we want number of paths from that vertex to each sink. Since k ≤ n ≤ 600, we can compute for all vertices to all sinks in O(n * (n + m)?) Actually we can compute DP for each source separately, but that would be O(k * (n+m)) which could be up to 600*1e5 = 60 million, which is okay. But we might also do a more efficient DP: we can compute for each vertex v, an array cnt[v][j] for j=1..k (or for sinks only) representing number of paths from v to sink j. Then we can compute these by processing vertices in reverse topological order (starting from sinks). But we need to consider multiple edges: from v, we sum over all outgoing edges (with multiplicities) the counts from the neighbor. Also, if v itself is a sink (i.e., v is in sinks list), then there is a trivial path from v to itself: add 1 to cnt[v][index_of_v_in_sinks] (if v is sink). But careful: The trivial path (length 0) is only counted if we are counting paths from v to v. For other sinks, not relevant. So we can initialize cnt[v] = 0 for all v. Then in reverse topological order (i.e., processing vertices in order of decreasing topological number, i.e., from sinks backwards), we can compute: For each vertex v, we set cnt[v][sink_index_of_v] = 1 if v is a sink. Then for each outgoing edge (v->u, multiplicity mult), we add mult * cnt[u] to cnt[v] (component-wise). Because any path from v to a sink j can go via an edge v->u (there are mult choices for which edge) and then any path from u to j.
We need to do this for all vertices. This yields for each vertex v, the number of paths from v to each sink j. That's exactly what we need for sources. Complexity: O((n + m) * k). Since n ≤ 600, m ≤ 1e5, k ≤ 600, that's at most 6e7 operations, which might be borderline but likely okay in C++ (maybe fine). But we need to mod p. However, k=600, m=1e5 => 60 million additions and multiplications, which is okay (given time limit unknown but typical 2 sec? Probably okay with optimization). But we need to store cnt for each vertex: an array of size k (600) for each of 600 vertices => 360k integers, fine.
Alternatively, we could compute only for sources, but the reverse DP from all vertices is easier.
We must be careful about order: We need to process vertices in reverse topological order (i.e., ensure that when processing v, all its outgoing neighbors u have been processed already, so that cnt[u] is final). Since we are going from sinks backwards, we can do topological sort (Kahn) to get order, then iterate vertices in reverse order.
But note: Graph may have multiple edges, but that's fine; we can store adjacency list with multiplicities: for each vertex, a list of (neighbor, count). Since m up to 1e5, storing each edge individually is fine. But to aggregate counts, we could compress.
Implementation steps:
-
Read n, m, p.
-
Initialize indegree array of size n+1, outdegree? We need both for source/sink identification.
-
Also, we need to build adjacency list for reverse DP. Actually for DP we need outgoing edges from each vertex; we have that.
-
Also we need to compute topological order. Since graph is acyclic, we can compute using Kahn's algorithm (queue). We'll compute indegree (for topological sorting) as the number of incoming edges. But careful: we already have indegree for source identification; but that indegree counts incoming edges. For Kahn we need indegree to process in forward order. So we can compute indegree array (count of incoming edges) and outdegree (count of outgoing edges) from edge list.
-
Build adjacency list: For each edge (a,b), add b to adj[a] (or store b and count). Since multiple edges, we can either store each edge individually, then during DP, for each edge (v,u) we add cnt[u] to cnt[v] multiplied by 1 (since each edge is distinct). That is, we can just loop over all edges from v, each time add cnt[u] to cnt[v] (mod p). That would be O(m * k) which is 1e5 * 600 = 60 million, similar to O((n+m)*k). So it's fine.
But we can also compress: For each v, we can group edges by u and store multiplicity to reduce loops if many parallel edges. However, m is only 1e5, and k is 600, so 60 million operations is okay. But note: In DP, we will for each vertex v, iterate over all outgoing edges, and for each edge, add cnt[u] (vector of size k) to cnt[v]. That's m * k = up to 60 million adds, which is fine in C++ within 1 sec? Possibly borderline but still okay with simple loops and mod p. 60 million ~ 0.06 billion, should be okay. However, we also have to consider that each addition is modulo p, and we need to multiply by multiplicity if we compress. But if we store each edge individually, each edge contributes one addition of the whole vector? Actually for each edge, we need to add cnt[u] to cnt[v] (component-wise). That would be O(k) per edge, total O(m*k). That's 60 million integer additions and maybe mod operations; okay.
But careful: In DP, we will process vertices in reverse topological order. For each vertex v, we will have an array cnt[v] of size k (maybe a vector of longs). We'll initialize zeros. Then we set cnt[v][sink_index(v)] = 1 if v is sink. Then we iterate over each outgoing edge (v->u). Since we process in reverse topological order, u is after v in topological order? Actually topological order: if we have edge v->u, then v comes before u in topological order. In reverse order, we process u before v (since we need cnt[u] computed). So we need to process vertices in reverse topological order. So we compute topological order (list) from Kahn (queue) that gives order from sources to sinks. Then we iterate vertices from end to start.
For each vertex v in reverse order:
- if v is sink: set cnt[v][sink_idx[v]] = 1
- for each edge v->u in adjacency list of v: (since we are in reverse order, u has been processed already) we do: for j in 0..k-1: cnt[v][j] = (cnt[v][j] + cnt[u][j]) % p; But this adds exactly one per edge. However, this would add the same cnt[u] multiple times if multiple edges. That's correct because each edge gives a distinct path.
But careful: For a path from v to sink j: If there are multiple edges v->u, each gives a distinct way to go from v to u, and then any path from u to j yields distinct paths. So yes, we need to add cnt[u] for each edge, not just once.
Now, if we compress edges, we can do: cnt[v][j] += mult * cnt[u][j] mod p.
But either way.
Now after DP, for each source i (vertex s = sources[i]), we have cnt[s] vector. Then M[i][j] = cnt[s][j] (where j index corresponds to sink index). Since we computed cnt[v] for each vertex, we can extract.
Now we need to compute determinant of M modulo p. Since p is prime, we can perform Gaussian elimination modulo p. But p could be up to 1e9+7, which fits 64-bit. However, p may be small (like 2)? It's prime, so could be 2. But that's okay; we can use modular arithmetic with long long, careful with multiplication mod p (since p up to 1e9+7, product of two up to (p-1)^2 fits in 64-bit if p<=1e9+7 => (1e9+7)^2 ~ 1e18+ something, still less than 2^63-1 (9.22e18) so safe in signed 64-bit. So we can use long long.
But note: We might need to compute modular inverse for pivot, but since p is prime, we can compute modular inverse via extended gcd or powmod.
However, the matrix entries are computed modulo p. But we need to compute determinant mod p. Standard Gaussian elimination over field: for each row, find a pivot (non-zero entry) in current column, swap rows if needed, multiply row by inverse of pivot to make it 1 (optional), then eliminate below. For determinant, we can avoid making pivot 1 and just perform elimination using the pivot as is, tracking row swaps and multiplication factors. The determinant after elimination is product of pivots (if we perform elimination without scaling rows). Actually we can perform elimination by: for each column j, find pivot row i >= j with non-zero entry. Swap row i with row j, determinant sign flips. Then for rows below, eliminate by row[k] = row[k] - (a_{kj} / a_{jj}) * row[j]. That does not change determinant (since we are adding multiples of row j). At the end, determinant = product of diagonal entries (after swaps) times (-1)^{number of swaps}. But this works over a field as long as we use division: we need to multiply by inverse of pivot. Alternatively, we can avoid division and keep track of a factor, but using modular inverse is simpler.
Since p may be large but prime, we can compute modular inverse using powmod(pivot, p-2, p). However, if p is large, exponentiation is O(log p), which for each pivot could be up to 600 times, fine.
But note: p could be up to 1e9+7, which fits 32-bit? 1e9+7 > 2^31-1? Actually 2^31-1 = 2147483647, so 1e9+7 = 1000000007 < 2147483647, so fits in 32-bit signed int. So we can use int for mod operations if careful with multiplication overflow. But we can use long long for safety.
But there is a catch: p may be as large as 1e9+7? The input says p is prime, 2 ≤ p ≤ 10^9+7. Actually it says (2 ≤ p ≤ 10^9 + 7). So p could be up to 1,000,000,007. So within 32-bit signed? 1,000,000,007 < 2^31-1, so yes fits in signed int. But to multiply two ints we might overflow 32-bit, so use long long.
Now, we must consider the case when the determinant is negative. We need answer modulo p as non-negative. So after computing determinant mod p, we adjust: (det % p + p) % p.
Edge cases: If k = 0? But number of sources and sinks same, could be zero? If there are no sources and no sinks? That would happen if graph has cycles? But graph acyclic, but could have no source? In a finite DAG, there must be at least one source and one sink unless n=0 (n≥1). So k≥1? Possibly n=1 with no edges: vertex is both source and sink, then k=1. So okay.
Now, we must confirm that the LGV lemma is applicable exactly as stated. There is one nuance: The LGV lemma counts families of vertex-disjoint paths where each source is matched to a sink. However, it assumes that the paths are considered as sets of vertices/edges and each family's weight is product of path weights. In our problem, two sets are considered different if there is an edge that lies in one but not the other. That matches the definition: each family is a set of paths, and each path is a sequence of edges. So the weight of a path is 1 per path, but multiple edges give multiple distinct paths, consistent with our counting.
But LGV lemma also requires that the number of families of intersecting paths cancel out in the determinant expansion, which relies on the sign of permutations. The lemma holds for any acyclic directed graph with any weight function (commutative ring). So it's valid.
Thus answer = det(M) mod p.
But wait: Is there any possibility that some sets of vertex-disjoint paths are counted multiple times in M matrix? The determinant expansion includes terms for every permutation σ, each term is product of M_{i,σ(i)}. Each such product counts families of paths where we choose a path from source i to sink σ(i) for each i, but these paths may intersect. The LGV lemma says that the sum over all such choices, weighted by sign(σ), equals the sum over only non-intersecting families of sign(σ). That's the magic. So determinant of M indeed gives the desired signed sum. So the answer is det(M) mod p.
Thus we are done.
However, we must be cautious about multiple edges and path counting: For counting M_{ij}, we count all directed paths (including those that may use vertices that are sources or sinks other than the endpoints). That's fine.
Now, let's test with the sample inputs.
Sample 1:
n=4, edges: 1->3, 2->4.
Sources: 1,2 (indeg 0). Sinks: 3,4 (outdeg 0). k=2.
Compute number of paths:
From source1 (vertex1) to sink1 (vertex3): only path: 1->3 => 1.
to sink2 (vertex4): no path? 1->3 only to 3, cannot reach 4. So 0.
From source2 (vertex2) to sink1 (vertex3): no path. to sink2 (vertex4): 2->4 =>1.
So M = [[1,0],[0,1]]. Determinant = 1. mod p=1000003 =>1. Output 1. matches.
Sample2:
Edges: 4->1, 3->2.
Sources: indeg 0: vertices with no incoming: which are? Check indeg: 1 gets from 4, so indeg1=1; 2 gets from 3, indeg2=1; 3 has indeg? no edge to 3 => indeg3=0; 4 indeg4=0. So sources: 3,4 (sorted: 3,4). Sinks: outdeg 0: vertices with no outgoing: 1 (outdeg0), 2 (outdeg0). So sinks:1,2.
Compute paths:
From source 3 (vertex3) to sink1 (vertex1): any path? 3->2 only, cannot reach 1. So 0.
to sink2 (vertex2): 3->2 => 1.
From source 4 (vertex4) to sink1 (vertex1): 4->1 =>1.
to sink2 (vertex2): no path. So M=[[0,1],[1,0]]. Determinant = -1 mod p = p-1 = 1000002. matches.
Sample3:
n=4, edges: 2->1,2->4,3->1,3->4.
Sources: indeg0: 2,3. Sinks: outdeg0: 1,4.
Paths:
From 2 to 1: 2->1 =>1; also 2->4->? 4 has no outgoing, so not to 1. So only 1.
From 2 to 4: 2->4 =>1.
From 3 to 1: 3->1 =>1.
From 3 to 4: 3->4 =>1.
So M=[[1,1],[1,1]]. Determinant = 11 - 11 = 0. Output 0. matches.
Sample4:
n=6 edges: 1->4,1->5,1->6,2->6,3->6.
Sources: indeg0: vertices: 1? indeg? No incoming? Actually check: vertices 1,2,3 have no incoming; 4,5,6 have incoming from 1,2,3. So sources: 1,2,3.
Sinks: outdeg0: vertices with no outgoing: 4? 4 has no outgoing? edges from 4? none. So outdeg4=0; 5 outdeg0; 6 outdeg0? Actually 6 has outgoing? edges listed: 1->6,2->6,3->6, but 6 has no outgoing edges listed, so outdeg6=0. So sinks:4,5,6.
Paths:
From 1: to 4: 1->4 =>1. to5: 1->5=>1. to6: 1->6=>1.
From 2: to4: no? 2->6 only, cannot reach 4 or 5. So 0 to 4,0 to5, 1 to6.
From 3: similarly 0 to4,0 to5,1 to6.
M = [[1,1,1],[0,0,1],[0,0,1]]? Actually source order: [1,2,3]; sink order: [4,5,6]. So:
Row1 (source1=1): to sink4:1, sink5:1, sink6:1.
Row2 (source2=2): to 4:0,5:0,6:1.
Row3 (source3=3): to 4:0,5:0,6:1.
Matrix:
[1,1,1]
[0,0,1]
[0,0,1]
Determinant? Compute: third column subtract? Actually determinant of this 3x3:
det = 1*(01 - 01) -1*(01 - 01) + 1*(00 - 00) = 0. So answer 0. matches.
Sample5:
n=5 edges: 5->1, 3->4.
Sources: indeg0: 2,3,5 (since 2 has no incoming, 3 no incoming, 5 no incoming). Sinks: outdeg0: 1,2,4 (1 no outgoing, 2 no outgoing, 4 no outgoing). So sources sorted: [2,3,5]; sinks sorted: [1,2,4].
Now compute paths:
We must include trivial paths: from a vertex to itself if it is both source and sink. Vertex 2 is both source and sink. So from source 2 to sink 1: paths? 2 has no outgoing edges (except maybe? none), so cannot reach 1. So 0.
From source 2 to sink 2: trivial path (length 0) =>1.
From source 2 to sink 4: cannot reach 4 =>0.
From source 3 to sink1: 3 has outgoing to 4 only; 4 has no outgoing; cannot reach 1; so 0.
From source 3 to sink2: 3->? none to 2 =>0.
From source 3 to sink4: 3->4 =>1 (plus maybe trivial if 3=4? no). So 1.
From source 5 to sink1: 5->1 =>1.
From source 5 to sink2: 5->1 only, cannot reach 2 =>0.
From source 5 to sink4: 5->1->? no =>0.
So M =
[0,1,0]? Actually row1 source=2: col1 sink=1:0; col2 sink=2:1; col3 sink=4:0 => [0,1,0]
row2 source=3: [0,0,1]
row3 source=5: [1,0,0] (since sink1:1, sink2:0, sink4:0) => [1,0,0]
Matrix:
2->? Actually reorder: rows: (2,3,5); columns: (1,2,4)
Row1 (2): [0,1,0]
Row2 (3): [0,0,1]
Row3 (5): [1,0,0]
Determinant =? Compute permutation: For identity (1->1,2->2,3->3) gives 000=0. Other permutations: (1->2,2->3,3->1): entries (1,2)=1, (2,3)=1, (3,1)=1 => product=1, sign of permutation (1 2 3) => is it even? (1->2,2->3,3->1) is a 3-cycle, sign? A 3-cycle is even? 3-cycle can be expressed as 2 transpositions => even? Actually parity: a cycle of length L can be written as L-1 transpositions; so length 3 => 2 transpositions => even => sign +1? Wait sign = (-1)^{L-1} = (-1)^2 = +1. So product 1 * sign +1 = 1. Any other permutation? (1->3,2->1,3->2): entries (1,3)=0 (since row1 col3=0) product 0. So determinant = 1. So answer 1 mod p =1. matches.
Thus LGV works.
Thus solution is straightforward.
Now we must implement:
-
Input edges: store edges as adjacency list for forward direction (since we need outgoing edges for DP). Also compute indegree and outdegree. For indegree we count incoming edges; for outdegree outgoing edges.
-
Identify sources: vertices v (1-indexed) such that indegree[v] == 0. Sinks: outdegree[v] == 0. Sort them.
-
Assign index to sinks: map sink vertex -> column index (0..k-1). We'll need for DP to initialize cnt[v][col] = 1 if v is sink.
-
Topological order: Use Kahn's algorithm. Since graph may have multiple edges, indegree counts duplicates; but for topological sort we need number of incoming edges as indegree. We'll compute indegree_for_topo = indegree (incoming count). But careful: indegree array we computed earlier counts incoming edges, but it's the same. However, we must be careful: We already have indegree from edge list. We'll use that for topological sort. Steps: create a queue, push all vertices with indegree == 0. While queue not empty, pop u, add to order, for each outgoing edge (u->v), decrement indegree[v] by 1 (or by the multiplicity? If multiple edges, each edge contributes 1 to indegree, so we need to decrement indegree[v] by the number of edges from u to v. So we must know the multiplicity. So we can store adjacency list with each edge individually; while doing topological sort, we can loop over each edge from u, and for each, decrement indegree[v] by 1. That's fine. Since we might have many edges, total O(m) work.
Alternatively, we can compute topological order using DFS-based method. But Kahn is fine.
Now after obtaining topological order (list), we'll process vertices in reverse order.
- DP: Initialize cnt as a vector of vectors: cnt[n+1][k] maybe as a 2D array using vectors for memory efficiency. Since n <= 600 and k <= 600, we can allocate static arrays: long long cnt[601][601] perhaps. But we need for each vertex, only store for sinks. We'll allocate a 2D array of size (n+1) x k, where k is at most n. 601x601 = 361k entries, each 8 bytes = ~3MB, fine.
We'll also have an array is_sink boolean and sink_index mapping.
Initialize all cnt[v][j] = 0.
Then for v in reverse topological order:
if (is_sink[v]) {
idx = sink_idx[v];
cnt[v][idx] = 1; // trivial path from v to itself
}
For each outgoing edge (v->u) (iterate over adjacency list of v):
for j in 0..k-1:
cnt[v][j] = (cnt[v][j] + cnt[u][j]) % p;
But note: This adds cnt[u][j] for each edge. However, we also need to consider that multiple edges from v to u cause multiple additions. So we just loop over each edge individually. That's fine.
But careful: The DP order: we process vertices in reverse topological order (i.e., from sinks to sources). So when we process v, all its successors u have been processed already because topological order ensures u appears after v? Actually topological order is such that if there's an edge v->u, then v appears before u. So in reverse order, u appears before v. So we process u before v. Good.
Edge Cases: There might be self-loops? Graph is acyclic, so no self-loops.
Now after DP, we can build M: for each source i (sorted list sources), we take its vertex s, and for each sink j (sorted list), M[i][j] = cnt[s][j] mod p. But we already have cnt[v][j] for each v.
Now compute determinant modulo p.
We'll implement Gaussian elimination for a k x k matrix over field mod p.
Since p is prime, we can compute modular inverses.
Algorithm:
Let A be a copy of M (we can modify in place). We'll compute det = 1.
For col = 0 to k-1:
Find pivot row r >= col with A[r][col] != 0 mod p.
If not found, det = 0, break.
If r != col, swap rows r and col, det = det * (-1) mod p (i.e., multiply by p-1 mod p).
pivot = A[col][col].
det = det * pivot % p.
Now we want to eliminate below (and above? only below for row-echelon, but for determinant we only need product of diagonal after elimination? Actually if we only eliminate below, the determinant changes? Typically we do: for i from col+1 to k-1:
factor = A[i][col] * inv(pivot) % p
for j from col to k-1: // we can start from col because left of col are zero after previous steps?
A[i][j] = (A[i][j] - factor * A[col][j]) % p
// we don't need to update above rows.
At the end, the diagonal entries are the pivots after elimination? But after elimination, the matrix becomes upper triangular. The product of diagonal entries is the determinant only if we didn't scale rows. However, we multiplied each elimination step by factor and subtract, which doesn't change determinant. But we also multiplied det by pivot earlier. However, if we then perform row operations that modify the pivot row? We didn't scale pivot row. So after elimination, the matrix is upper triangular, but the diagonal entries are not necessarily the original pivots? Actually, after we performed elimination using the pivot row (without scaling it), the pivot row remains unchanged. For rows below, we subtract multiples of the pivot row. This operation does not change determinant. At the end, the matrix becomes upper triangular, and the diagonal entries of the rows we processed become the pivots themselves (since we haven't changed the pivot row). For subsequent columns, when we process column col, we have already zeroed out entries below in previous columns. The pivot row for col remains with A[col][col] = pivot. The elimination for rows below only affects columns >= col, so after elimination, A[col][col] remains pivot. For rows i>col, we subtract factor*A[col][col] from A[i][col], making A[i][col] zero. So after processing all columns, the matrix is upper triangular with the diagonal entries being the pivots we used (the original A[col][col] at the time of pivot selection, but note that after previous steps, the pivot row might have been modified by earlier eliminations? Actually when we process column col, the rows col..k-1 have been modified by earlier eliminations, but the pivot row (col) may have been modified by earlier steps? In standard Gaussian elimination (with partial pivoting), when we process column col, we consider rows from col to end. The row col might have been modified from earlier eliminations when it was below a pivot? Actually in the standard algorithm, we start with row 0 as pivot row for column 0. After elimination, rows 1..k-1 are modified, but row 0 remains unchanged for columns >=0. Then for column 1, we consider rows 1..k-1, and row 1 may have been modified, but that's okay; we use its current value as pivot. So the diagonal entries after processing become the pivots we used at each step. So if we multiply det by the pivot value at each step, and then perform elimination, the determinant of the resulting upper triangular matrix is the product of the pivots (since the diagonal entries are the pivots). However, we also performed row swaps, which multiply determinant by -1 each. So det final = product of pivots * (-1)^{#swaps}. So we can compute det incrementally: det = 1; for each column, after swap, pivot = A[col][col]; if pivot==0, det=0; else det = det * pivot % p; then eliminate below. But careful: After we multiply det by pivot, we must not also multiply by the subsequent scaling of rows because we don't scale rows. That's correct.
Alternative: Compute determinant via standard algorithm: perform Gaussian elimination to upper triangular form, keeping track of row swaps. At the end, multiply diagonal entries, adjust sign. That's easier: we perform elimination without scaling, but we may need to divide when performing row operations? Actually to eliminate, we compute factor = A[i][col] / A[col][col]. That requires division (multiplication by inverse). So we need modular inverse. That's fine.
But note: When we compute factor = A[i][col] * inv(pivot) % p, and then A[i][j] -= factor * A[col][j] mod p, we are effectively performing a row operation that doesn't change determinant. So after we have upper triangular, the diagonal entries are not necessarily the original pivots because we might have changed them in later steps? Actually, for row i (i>col), after elimination, its diagonal entry at column i will be updated later. But for the current pivot row col, its diagonal entry remains pivot (since we only subtract multiples of it from rows below, but we never change it). For later columns, when we process column col2 > col, we will modify rows col2..k-1, including the pivot rows from earlier? No, we only eliminate below the current pivot. So the pivot row col will not be modified in later steps because for later columns, we only consider rows with index >= col2, and col < col2, so row col is not touched. So the diagonal entries become the pivots we used. So product of diagonal after elimination equals product of pivots. So we can compute determinant as product of diagonal entries times sign of row swaps.
Implementation details:
We need to handle modulus p. Since p is prime but could be small (e.g., p=2). In that case, modular inverse of non-zero element mod 2 is just 1. So fine.
Edge Cases: If k=0? Not possible? Could be if no sources? But then k=0 and we need answer? The problem says number of sources equals number of sinks, but could be zero? Possibly if all vertices have both incoming and outgoing? In a finite DAG, there must be at least one source and one sink unless n=0 (n>=1). Actually a non-empty DAG always has at least one source and at least one sink. So k>=1.
Thus algorithm:
- Input n,m,p.
- Initialize arrays: indegree[n+1] = 0, outdegree[n+1] = 0. Adjacency list: vector<vector> adj(n+1) perhaps store neighbors (and possibly counts? but for topological sort and DP we need to iterate over each edge individually. We'll store adjacency list of edges: for each vertex v, a vector neigh; but if multiple edges, we need each edge separately to add cnt[u] for each edge. So we can store a vector of neighbors (maybe store as vector to) for each v, and we can push each occurrence. That is memory O(m) ~1e5, fine.
But we also need indegree for topological sort. While reading edges, for each edge (a,b), we increment outdegree[a]++, indegree[b]++, and add b to adj[a].
We also may later need to know number of edges from a to b for DP; but we can simply iterate over each occurrence. That's fine.
-
After reading edges, compute sources: list of vertices v from 1..n with indegree[v]==0, sorted ascending. Similarly sinks: list of vertices with outdegree[v]==0, sorted ascending. Let k = sources.size(). Should equal sinks.size(); if not, problem guarantees it.
-
Create map sink_index: for i from 0 to k-1, sink_index[sinks[i]] = i.
-
Topological sort: Compute indegree_topo = indegree (copy). Use queue. We'll produce order list (vector topo). While queue not empty: pop u, add to topo, for each v in adj[u], decrement indegree_topo[v] by 1;