#P6178. 【模板】Matrix-Tree 定理

    ID: 5132 远端评测题 1000ms 250MiB 尝试: 0 已通过: 0 难度: 8 上传者: 标签>图论矩阵树定理生成树高斯消元

【模板】Matrix-Tree 定理

Description

Given a weighted graph with nn vertices and mm edges (it may be undirected or directed).

Define the weight of a spanning tree TT as the product of the weights of all edges in TT.

Find the sum of the weights of all distinct spanning trees, modulo 109+710^9+7.


Notes:

  1. In this problem, a spanning tree of a directed graph means an out-arborescence rooted at 11.

  2. Two spanning trees T1,T2T_1, T_2 are different if and only if there exists an edge ee such that eT1e\in T_1 and eT2e\notin T_2.

Input Format

The first line contains three integers n,m,tn, m, t, representing the number of vertices, the number of edges, and the type of the graph (t=0t=0 for an undirected graph, t=1t=1 for a directed graph).

The next mm lines each contain three integers u,v,wu, v, w.

If t=0t=0, it means there is an undirected edge between uu and vv with weight ww.

If t=1t=1, it means there is a directed edge from uu to vv with weight ww.

Output Format

The first line contains one integer ansans, which is the sum of spanning tree weights of the given graph modulo 109+710^9+7.

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 11 Explanation]

The undirected graph in sample 11 is shown in the left figure:

The right figure shows an example spanning tree with weight 3×1×2×3=183\times 1\times 2\times 3=18.


[Sample 22 Explanation]

The directed graph in sample 22 is shown in the left figure:

The right figure shows an example spanning tree (an out-arborescence rooted at 11) with weight 1×1×1×2=21\times 1\times 1\times 2=2.


[Constraints]

For 100%100\% 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 1,2,3,4,5,61,2,3,4,5,6, t=0t=0; for test points 7,8,9,10,117,8,9,10,11, t=1t=1.

The graph may contain multiple edges and self-loops. Multiple edges are counted as different edges.

Translated by ChatGPT 5