SPOJ104 HIGH

本文版权归ljh2000和博客园共有,欢迎转载,但须保留此声明,并给出原文链接,谢谢合作。

本文作者:ljh2000
作者博客:http://www.cnblogs.com/ljh2000-jump/
转载请注明出处,侵权必究,保留最终解释权!

题目链接:SPOJ104

正解:矩阵树定理+高斯消元

解题报告:

  写的第一发$Matrix-Tree$定理题QAQ

  这道题要求一张无向图的生成树个数,既然是模板题,窝直接上结论辣:构造一个新的矩阵:度数矩阵-邻接矩阵,

  对这个新的矩阵去掉第$r$行、第$r$列之后得到的矩阵,高斯消元,消成上三角的形式(也就是左下角都是$0$),然后主对角线上的数的乘积就是答案了…

  两点注意事项:

  1、最后答案要取绝对值;

  2、发现$a[i][i]=0$时会出现$/0$这种尴尬事情,同时这也意味着我可以直接$return 0$了,因为主对角线上已经出现了$0$。

//It is made by ljh2000
//有志者,事竟成,破釜沉舟,百二秦关终属楚;苦心人,天不负,卧薪尝胆,三千越甲可吞吴。
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <ctime>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <string>
#include <complex>
#include <bitset>
using namespace std;
typedef long long LL;
typedef long double LB;
typedef complex<double> C;
const double pi = acos(-1);
const int MAXN = 12;
int n,m;
LB a[MAXN][MAXN],ans;

inline int getint(){
    int w=0,q=0; char c=getchar(); while((c<'0'||c>'9') && c!='-') c=getchar();
    if(c=='-') q=1,c=getchar(); while (c>='0'&&c<='9') w=w*10+c-'0',c=getchar(); return q?-w:w;
}

inline void Gauss(int n){
	for(int i=0;i<n;i++) {
		for(int j=i+1;j<n;j++) {
			if(a[i][i]==0) { ans=0; return ; }//!!!
			LB t=a[j][i]/a[i][i];
			for(int k=i;k<n;k++) {
				a[j][k]-=a[i][k]*t;
			}
		}
	}

	for(int i=0;i<n;i++)
		ans*=a[i][i];
}

inline void work(){
	int T=getint(); int x,y;
	while(T--) {
		n=getint(); m=getint(); ans=1;
		memset(a,0,sizeof(a));
		for(int i=1;i<=m;i++) {
			x=getint(); y=getint(); x--; y--;
			a[x][y]--; a[y][x]--;
			a[x][x]++; a[y][y]++;
		}
		Gauss(n-1);
		ans=fabs(ans);//!!!
		printf("%.0Lf
",ans);
	}
}

int main()
{
    work();
    return 0;
}
//有志者,事竟成,破釜沉舟,百二秦关终属楚;苦心人,天不负,卧薪尝胆,三千越甲可吞吴。

  

原文地址:https://www.cnblogs.com/ljh2000-jump/p/6522862.html