当前位置: 代码迷 >> 综合 >> SP104 HIGH - Highways(基尔霍夫矩阵,生成树个数)
  详细解决方案

SP104 HIGH - Highways(基尔霍夫矩阵,生成树个数)

热度:37   发布时间:2024-02-07 19:39:49.0

题目描述
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.

题意翻译
题目描述
给定一张无向图,求出其生成树的个数 (请使用Matrix定理求解)

输入输出格式
输入格式:
第一行一个整数T,表示测试数据的个数 每个测试数据第一行给出n,mn,m 分别表示点数与边数 接下来mm 行,每行给出两个数a,ba,b ,表示a,ba,b 之间有一条无向边

输出格式:
每个测试数据,输出一个整数,表示给出的无向图的生成树的个数

输入输出样例
输入 #1复制
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
输出 #1复制
8
1
1
3

思路:
A-B=C。
A代表度数方程,B代表邻接矩阵,C代表基尔霍夫矩阵。
矩阵树定理为将基尔霍夫矩阵去掉一行或一列后求得的行列式结果为生成树个数。

参考
https://www.cnblogs.com/wsy107316/p/12825699.html

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
#include <stack>
#include <vector>
#include <set>using namespace std;typedef long long ll;
const int maxn = 20 + 7;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;int deg[maxn][maxn],vis[maxn][maxn];
ll a[maxn][maxn];void init() {memset(deg,0,sizeof(deg));memset(a,0,sizeof(a));memset(vis,0,sizeof(vis));
}ll det(int n) { //计算行列式的值ll res = 1;for(int i = 2;i <= n;i++) { //去掉第一行for(int j = i + 1;j <= n;j++) {while(a[j][i]) {ll t = a[i][i] / a[j][i];for(int k = i;k <= n;k++) {a[i][k] = (a[i][k] - a[j][k] * t);}for(int k = i;k <= n;k++) {swap(a[i][k],a[j][k]);}res = -res;}}if(a[i][i] == 0) return 0;res = res * a[i][i];}return abs(res);
}int main() {int T;scanf("%d",&T);while(T--) {init();int n,m;scanf("%d%d",&n,&m);for(int i = 1;i <= m;i++) {int x,y;scanf("%d%d",&x,&y);a[x][x]++;a[y][y]++;a[x][y]--;a[y][x]--;}printf("%lld\n",det(n));}return 0;
}
  相关解决方案