1016: [JSOI2008]最小生成树计数
Time Limit: 1 Sec Memory Limit: 162 MBSubmit: 6702 Solved: 2731
[ Submit][ Status][ Discuss]
Description
现在给出了一个简单无向加权图。你不满足于求出这个图的最小生成树,而希望知道这个图中有多少个不同的
最小生成树。(如果两颗最小生成树中至少有一条边不同,则这两个最小生成树就是不同的)。由于不同的最小生
成树可能很多,所以你只需要输出方案数对31011的模就可以了。
Input
第一行包含两个数,n和m,其中1<=n<=100; 1<=m<=1000; 表示该无向图的节点数和边数。每个节点用1~n的整
数编号。接下来的m行,每行包含两个整数:a, b, c,表示节点a, b之间的边的权值为c,其中1<=c<=1,000,000,0
00。数据保证不会出现自回边和重边。注意:具有相同权值的边不会超过10条。
Output
输出不同的最小生成树有多少个。你只需要输出数量对31011的模就可以了。
Sample Input
4 6
1 2 1
1 3 1
1 4 1
2 3 2
2 4 1
3 4 1
1 2 1
1 3 1
1 4 1
2 3 2
2 4 1
3 4 1
Sample Output
8
不同的最小生成树相同权的边的个数一定是一样的, 可以用反证法证明。。
那我们就先求一遍最小生成树,把不同权值的 边的个数纪录一下。 然后把 每种边权的范围纪录一下,方便dfs。。
然后dfs爆搜所有情况,根据乘法原理。 就可以求出答案了
#include <iostream>
#include <stdio.h>
#include <vector>
#include <string.h>
#include <cmath>
#include <queue>
#include <algorithm>
#include <string>
#include <utility>
using namespace std;
const int INF = 0x3f3f3f3f;
const int maxn = 1050;
const int mod = 31011;
int total, cnt;
int n, m;
struct Edge {
int u, v, w;
}e[maxn];
struct Node {
int x, y, v;
}node[maxn];
bool cmp(Edge const& e1, Edge const& e2) {
return e1.w < e2.w;
}
int f[maxn];
int find(int x) {
if (f[x] == x)
return x;
return find(f[x]);
}
int sum;
void dfs(int x, int now, int k) {
if (now == node[x].y + 1) {
if (k == node[x].v)
sum++;
}
else {
int p = find(e[now].u), q = find(e[now].v);
if (p != q) {
f[p] = q;
dfs(x, now + 1, k + 1);
f[p] = p;
f[q] = q;
}
dfs(x, now + 1, k);
}
}
int main() {
//freopen("in.txt", "r", stdin);
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
for (int i = 1; i <= m; ++i)
cin >> e[i].u >> e[i].v >> e[i].w;
sort(e + 1, e + m + 1, cmp);
total = cnt = 0;
for (int i = 1; i <= n; ++i)
f[i] = i;
for (int i = 1; i <= m; ++i) {
if (e[i].w != e[i - 1].w) {
node[++cnt].x = i;
node[cnt - 1].y = i - 1;
}
int p = find(e[i].u), q = find(e[i].v);
if (p != q) {
f[p] = q;
node[cnt].v++;
total++;
}
}
node[cnt].y = m;
if (total != n - 1) {
cout << 0 << endl;
}
else {
int res = 1;
for (int i = 1; i <= n; ++i)
f[i] = i;
for (int i = 1; i <= cnt; ++i) {
sum = 0;
dfs(i, node[i].x, 0);
res = (res * sum) % mod;
for (int j = node[i].x; j <= node[i].y; ++j) {
int q = find(e[j].u), p = find(e[j].v);
if (q != p) {
f[q] = p;
}
}
}
cout << res << endl;
}
}