[spoj104][Highways] (生成树计数+矩阵树定理+高斯消元)

时间:2022-03-13 20:57:18

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:

Sample output:

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[][],B[][];
double a[][];
void gauss(){
int now=;
for(int i=;i<=n;i++){
int x=now;
while(fabs(a[x][now])<eps && x<=n)++x;
if(x==n+){puts("");return;}
for(int j=;j<=n;j++)
swap(a[now][j],a[x][j]);
for(int j=now+;j<=n;j++){
double x=a[j][now]/a[now][now];
for(int k=;k<=n;k++)
a[j][k]-=a[now][k]*x;
}
++now;
}
double ans=;
for(int i=;i<=n;i++)
ans*=a[i][i];
printf("%.lf\n",fabs(ans));
}
int main(){
int T;
scanf("%d",&T);
while(T--){
memset(A,,sizeof(A));
memset(B,,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=;i<=n;i++)
for(int j=;j<=n;j++)
a[i][j]=A[i][j]-B[i][j];
gauss();
}
return ;
}