spoj 104 HIGH - Highways (矩阵树定理)



HIGH - Highways

no tags 

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
题解:裸上基尔霍夫矩阵
构造基尔霍夫矩阵。
基尔霍夫矩阵,等于无向图的度数矩阵-邻接矩阵。或者当i=j时,a[i][i]为结点的度数;i!=j时,如果存在边(vi,vj),那么a[i][j]=-1
•Matrix-Tree定理:
–对于一个无向图G,它的生成树个数等于其Kirchhoff矩阵任何一个n-1阶主子式的行列式的绝对值。
–所谓n-1阶主子式,就是对于任意一个r,将C的第r行和第r列同时删去后的新矩阵,用Cr表示。
然后用高斯消元,将n-1阶的矩阵消成上三角矩阵,行列式的值就是n-1阶矩阵对角线上a[i][i]的乘积。
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#define N 30
#define LL long long
#define eps 1e-7
using namespace std;
int n,m,t;
double a[N][N],ans;
void guass(int n)
{
	for (int i=1;i<=n;i++) {
		int pos=0; 
		for (int j=i;j<=n;j++)
		 if (fabs(a[j][i])>fabs(a[pos][i])) pos=j;
		for (int j=1;j<=n;j++) swap(a[i][j],a[pos][j]);
		for (int j=i+1;j<=n;j++) 
		if (fabs(a[j][i])>eps){
			double t=a[j][i]/a[i][i];
			for (int k=1;k<=n;k++)
			 a[j][k]-=t*a[i][k];
		}
	}
	ans=1;
	for (int i=1;i<=n;i++) ans*=a[i][i];
}
int main()
{
	freopen("a.in","r",stdin);
	scanf("%d",&t);
	while (t--) {
		scanf("%d%d",&n,&m);
		memset(a,0,sizeof(a));
		for (int i=1;i<=m;i++) {
			int x,y; scanf("%d%d",&x,&y);
			a[x][y]=a[y][x]=-1;
			a[x][x]++; a[y][y]++;
		}
		//for (int i=1;i<=n;i++,cout<<endl)
		// for (int j=1;j<=n;j++) cout<<a[i][j]<<" ";
		guass(n-1);
		//for (int i=1;i<=n;i++,cout<<endl)
		 //for (int j=1;j<=n;j++) cout<<a[i][j]<<" ";
		printf("%.0lf\n",fabs(ans));
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值