矩阵树定理
定义
- 邻接矩阵:\(A=(a_{ij})\),其中
\(a_{ij}\) 表示 \(i\) 到 \(j\) 有几条边相连。
- 度数矩阵:\(C=(c_{ij})\),为对角矩阵,其中 \(c_{ii}\) 表示 \(i\) 的度数。
- 基尔霍夫矩阵:\(D=C-A\)。
- 余子式:\(M_{ij}\) 表示去掉第 \(i\) 行第 \(j\) 列后得到矩阵的行列式。
定理
无向图的生成树个数等于其基尔霍夫矩阵 \(D\) 的任意余子式的行列式。
如果图不连通,那么任意余子式为0。
例题
P4208 [JSOI2008]
最小生成树计数
根据定理,我们只需要求出联通的边权相同的点集,在该集合中根据矩阵树定理求出生成树的多少,然后把所有集合的结果相乘就好辣!
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 
 | #include<iostream>#include<cstdio>
 #include<algorithm>
 #include<cstring>
 #include<cctype>
 #include<cmath>
 using namespace std;
 inline int read(){
 int x=0,w=0;char c=getchar();
 while(!isdigit(c))w|=c=='-',c=getchar();
 while(isdigit(c))x=(x<<3)+(x<<1)+(c^48),c=getchar();
 return w?-x:x;
 }
 namespace star
 {
 const int maxn=105,maxm=1005,mod=31011;
 int n,m,N;
 int a[maxn][maxn],fa[maxn],but[maxn],bel[maxn];
 struct Edge{
 int u,v,w;
 bool operator < (const Edge& rhs) const{
 return w<rhs.w;
 }
 }e[maxm],em[maxm];
 int find(int x){return x==fa[x]?x:fa[x]=find(fa[x]);}
 
 long long Gauss(int n){
 long long ans=1;
 for(int i=1;i<=n;i++){
 for(int j=i+1;j<=n;j++){
 while(a[j][i]){
 long long t=a[i][i]/a[j][i];
 for(int k=i;k<=n;k++) a[i][k]=(a[i][k]-t*a[j][k]%mod+mod)%mod;
 swap(a[i],a[j]);
 ans=-ans;
 }
 }
 ans=(ans*a[i][i]%mod+mod)%mod;
 }
 return ans;
 }
 
 inline void work(){
 n=read();m=read();
 for(int i=1;i<=n;i++) fa[i]=i;
 for(int i=1;i<=m;i++) e[i].u=read(),e[i].v=read(),e[i].w=read();
 sort(e+1,e+m+1);
 
 int cnt=0,cnte=0;
 for(int i=1;i<=m;i++){
 int x=find(e[i].u),y=find(e[i].v),z=e[i].w;
 if(x!=y){
 fa[x]=y;
 em[++cnte]=e[i];
 if(z!=but[cnt]) but[++cnt]=z;
 }
 }
 if(cnte!=n-1) return (void)puts("0");
 
 long long ans=1;
 
 for(int i=1;i<=cnt;i++){
 for(int j=1;j<=n;j++) fa[j]=j;
 for(int j=1;j<=cnte;j++) if(em[j].w!=but[i]) fa[find(em[j].u)]=find(em[j].v);
 N=0;
 for(int j=1;j<=n;j++) if(find(j)==j) bel[j]=++N;
 for(int j=1;j<=n;j++) bel[j]=bel[find(j)];
 memset(a,0,sizeof(a));
 for(int j=1;j<=m;j++) if(e[j].w==but[i]){
 int x=bel[e[j].u],y=bel[e[j].v];
 a[x][y]--,a[y][x]--;
 a[x][x]++;a[y][y]++;
 }
 ans=ans*Gauss(N-1)%mod;
 }
 printf("%lld\n",ans);
 }
 }
 signed main(){
 star::work();
 return 0;
 }
 
 |