#P6178. 【模板】Matrix-Tree 定理
【模板】Matrix-Tree 定理
Description
Given a weighted graph with vertices and edges (it may be undirected or directed).
Define the weight of a spanning tree as the product of the weights of all edges in .
Find the sum of the weights of all distinct spanning trees, modulo .
Notes:
-
In this problem, a spanning tree of a directed graph means an out-arborescence rooted at .
-
Two spanning trees are different if and only if there exists an edge such that and .
Input Format
The first line contains three integers , representing the number of vertices, the number of edges, and the type of the graph ( for an undirected graph, for a directed graph).
The next lines each contain three integers .
If , it means there is an undirected edge between and with weight .
If , it means there is a directed edge from to with weight .
Output Format
The first line contains one integer , which is the sum of spanning tree weights of the given graph modulo .
5 8 0
2 3 1
1 2 3
4 5 1
4 2 2
3 5 2
3 4 3
3 4 1
3 3 5
144
5 9 1
1 2 3
3 2 1
1 3 1
2 4 2
3 5 1
4 3 4
3 5 1
5 4 1
4 4 6
72
Hint
[Sample Explanation]
The undirected graph in sample is shown in the left figure:

The right figure shows an example spanning tree with weight .
[Sample Explanation]
The directed graph in sample is shown in the left figure:

The right figure shows an example spanning tree (an out-arborescence rooted at ) with weight .
[Constraints]
For of the testdata: $1\leq n\leq 300,\ \ 1\leq m\leq 10^5,\ \ t\in \{0,1\},\ \ 1\leq u,v\leq n,\ \ 1\leq w\leq 10^9$.
For test points , ; for test points , .
The graph may contain multiple edges and self-loops. Multiple edges are counted as different edges.
Translated by ChatGPT 5
京公网安备 11011102002149号