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.
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.
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.
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
生成树计数入门题,使用Matrix-Tree定理(Kirchhoff矩阵) 可以直接搞出来。定义G的度数矩阵D[G]是一个n*n的矩阵,并且满足:当i≠j时,dij=0;当i=j时,dij等于vi的度数。
定义G的邻接矩阵A[G]也是一个n*n的矩阵, 并且满足:如果vi、vj之间有边直接相连,则aij=1,否则为0。
那么G的Kirchhoff矩阵C[G]=D[G]-A[G]
然后呢,Kirchhoff矩阵其实就是一个行列式,这个行列式的值就是生成树的个数了。
关于行列式的值怎么求?有一种方法是分治求……我感觉要递归吧……考虑到编程复杂度和我机器的系统栈,没有写。我使用的是类似高斯消元的方法,做出一个倒三角样子的系数矩阵,
那么行列式的值就是一条对角线的乘积了。
依据: 行列式的任两行(或两列)互换,行列式变号 ←高斯消元过程有交换两行的,所以要记录一下结果的符号
用实数λ乘以一行(或列)后,所得到的行列式等于原来的行列式乘以λ。 ←所以可以高斯消元做……
Code:
program SPOJ_104; var C:array[1..100,1..100]of Extended; A,D:array[1..100,1..100]of longint; n,m,cases:longint; procedure swap(var a,b:Extended); var t:extended; begin t:=a;a:=b;b:=t; end; function zero(x:Extended):boolean; begin if x<0 then x:=-x; if x<1e-15 then exit(true); exit(false); end; procedure init; var i,j,x,y:longint; begin readln(n,m); fillchar(D,sizeof(D),0); fillchar(A,sizeof(A),0); fillchar(C,sizeof(A),0); for i:=1 to m do begin readln(x,y); inc(D[x,x]);inc(D[y,y]); A[x,y]:=1;A[y,x]:=1; end; for i:=1 to n do for j:=1 to n do C[i,j]:=D[i,j]-A[i,j]; end; function solve:extended; var ret,zoom:Extended; i,j,k,oper:longint; begin oper:=0; ret:=1; for i:=1 to n-1 do begin if zero(C[i,i]) then begin for j:=i+1 to n do if not zero(C[j,i]) then break; if (j=n)and zero(C[j,i]) then exit(0); for k:=i to n do swap(C[i,k],C[j,k]); inc(oper); end; ret:=ret*C[i,i]; for j:=i+1 to n do C[i,j]:=c[i,j]/c[i,i]; for j:=i+1 to n do begin for k:=i+1 to n do C[j,k]:=C[j,k]-C[i,k]*c[j,i]; end; end; if (oper and 1<>0) then ret:=-ret; exit(ret); end; begin readln(cases); while cases>0 do begin dec(cases); init; writeln(solve:0:0); readln; end; end.