[spoj104][Highways] (生成树计数+矩阵树定理+高斯消元)
Posted AronQi
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[spoj104][Highways] (生成树计数+矩阵树定理+高斯消元)相关的知识,希望对你有一定的参考价值。
In some countries building highways takes a lot of time... Maybe that‘s because there are many possiblities to construct a network of highways and engineers can‘t make up their minds which one to choose. Suppose we have a list of cities that can be connected directly. Your task is to count how many ways there are to build such a network that between every two cities there exists exactly one path. Two networks differ if there are two cities that are connected directly in the first case and aren‘t in the second case. At most one highway connects two cities. No highway connects a city to itself. Highways are two-way.
Input
The input begins with the integer t, the number of test cases (equal to about 1000). Then t test cases follow. The first line of each test case contains two integers, the number of cities (1<=n<=12) and the number of direct connections between them. Each next line contains two integers a and b, which are numbers of cities that can be connected. Cities are numbered from 1 to n. Consecutive test cases are separated with one blank line.
Output
The number of ways to build the network, for every test case in a separate line. Assume that when there is only one city, the answer should be 1. The answer will fit in a signed 64-bit integer.
Example
Sample input:
4 4 5 3 4 4 2 2 3 1 2 1 3 2 1 2 1 1 0 3 3 1 2 2 3 3 1
Sample output:
8 1 1 3
Solution
学了一下矩阵树定理,用来求解生成树问题。
矩阵一树定理(matrix-tree theorem)一个计数定理.若连通图G的邻接矩阵为A,将一A的对角线(i,i)元素依次换为节点V的度d(V,),所得矩阵记为M,则M的每个代数余子式相等,且等于G的支撑树的数目.这就是矩阵一树定理.
处理行列式的话,考虑高斯消元,用初等变换把M矩阵处理为上三角矩阵X,那么X的行列式就是对角线系数之积
#include<cmath> #include<cstdio> #include<cstring> #include<iostream> #define eps 1e-20 using namespace std; int n,m,A[15][15],B[15][15]; double a[15][15]; void gauss(){ int now=1; for(int i=1;i<=n;i++){ int x=now; while(fabs(a[x][now])<eps && x<=n)++x; if(x==n+1){puts("0");return;} for(int j=1;j<=n;j++) swap(a[now][j],a[x][j]); for(int j=now+1;j<=n;j++){ double x=a[j][now]/a[now][now]; for(int k=1;k<=n;k++) a[j][k]-=a[now][k]*x; } ++now; } double ans=1; for(int i=1;i<=n;i++) ans*=a[i][i]; printf("%.lf\n",fabs(ans)); } int main(){ int T; scanf("%d",&T); while(T--){ memset(A,0,sizeof(A)); memset(B,0,sizeof(B)); scanf("%d%d",&n,&m); n--; while(m--){ int u,v; scanf("%d%d",&u,&v); u--;v--; A[u][u]++;A[v][v]++; B[u][v]++;B[v][u]++; } for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) a[i][j]=A[i][j]-B[i][j]; gauss(); } return 0; }
以上是关于[spoj104][Highways] (生成树计数+矩阵树定理+高斯消元)的主要内容,如果未能解决你的问题,请参考以下文章