矩阵树+最小生成树
最下生成树计数
https://darkbzoj.tk/problem/1016
板子题,使用板子
#include<bits/stdc++.h>
//#include<gl/glut.h>
//#include<ctime>
#define ll long long
#define mes(a,b) memset(a,b,sizeof(a))
#define ctn continue
#define ull unsigned long long
//#pragma warning(disable:4996)
#define tgg cout<<"---------------"<<endl;
const ll linf = 9223372036854775807;
const int inf = 0x3f3f3f3f;
using namespace std;
const double pi = acos(-1);
const ll maxn = 1000 + 5;
const int mod = 31011;
const double eps = 1e-8;
const ull p = 131;
const ull pc = 13331;
inline ll gcd(int a, int b) {
while (b ^= a ^= b ^= a %= b);
return a;
}
struct Edge {
int u, v;
ll w;
bool operator <(const Edge& ed) const {
return w < ed.w;
}
}edge[maxn];
int findfa(int x, int f[]) {
int y = x;
while (f[x] != x) x = f[x];
while (f[y] != x) {
int z = f[y];
f[y] = x;
y = z;
}
return x;
}
int fa1[maxn], fa2[maxn];
bool vis[maxn];
int g[maxn][maxn];
int kir[maxn][maxn];//kirch mat
vector<int> v[maxn];
ll det(int nn) {
for(int i=0;i<nn;++i)
for (int j = 0; j < nn; ++j) {
kir[i][j] %= mod;
}
ll ret = 1ll;
for (int i = 1; i < nn; ++i) {
for (int j = i + 1; j < nn; ++j) {
while (kir[j][i]) {
ll t = kir[i][i] / kir[j][i];
for (int k = i; k < nn; ++k) kir[i][k] = (kir[i][k] - kir[j][k] * t) % mod;
swap(kir[i], kir[j]);
ret = -ret;
}
}
if (kir[i][i] == 0) return 0ll;
ret = (ret * kir[i][i]) % mod;
}
ret = (ret + mod) % mod;
return ret;
}
int main(int argc, char* argv[]) {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int n, m;
cin >> n >> m;
for (int i = 0; i < m; i++) {
int u, v, w;
cin >> u >> v >> w;
//g[u][v] ++;
//g[v][u] ++;
//g[v][v] ++;
//g[u][u] ++;
edge[i] = { u, v, w };
}
sort(edge, edge + m);
for (int i = 1; i <= n; i++) fa1[i] = i, vis[i] = false;
int wt = -1; // same weight edges
ll ans = 1;
for (int k = 0; k <= m; k++) {
if (k == m || edge[k].w != wt) {
for (int i = 1; i <= n; i++) {
if (vis[i]) {
int fai = findfa(i, fa2);
v[fai].push_back(i);
vis[i] = false;
}
}
for (int i = 1; i <= n; i++) {
if (v[i].size() > 1) {
for (int a = 1; a <= n; ++a) {
for (int b = 1; b <= n; ++b)
kir[a][b] = 0;
}
int len = v[i].size();
for (int a = 0; a < len; ++a) {
for (int b = a + 1; b < len; ++b) {
int aa = v[i][a];
int bb = v[i][b];
kir[b][a] -= g[aa][bb];
kir[a][b] = kir[b][a];
kir[a][a] += g[aa][bb];
kir[b][b] += g[aa][bb];
}
}
ll now = det(len);
ans = (ans * now) % mod;
for (int a = 0; a < len; ++a) fa1[v[i][a]] = i;
}
}
for (int i = 1; i <= n; ++i) {
fa1[i] = findfa(i, fa1);
fa2[i] = fa1[i];
v[i].clear();
}
if (k == m) break;
wt = edge[k].w;
}
int u = edge[k].u;
int v = edge[k].v;
int fu = findfa(u, fa1);
int fv = findfa(v, fa1);
if (fu == fv) ctn;
vis[fu] = vis[fv] = 1;
fa2[findfa(fu, fa2)] = findfa(fv, fa2);
++g[fu][fv];
++g[fv][fu];
}
bool flg = 0;
for (int i = 2; i <= n && !flg; ++i) {
if (fa2[i] != fa2[i - 1]) {
flg = 1;
}
}
if (m == 0) flg = 1;
if (flg) ans = 0;
ans %= mod;
cout << ans << endl;
return 0;
}