bzoj1016 [JSOI2008]最小生成树计数

Description

现在给出了一个简单无向加权图。你不满足于求出这个图的最小生成树,而希望知道这个图中有多少个不同的最小生成树。(如果两颗最小生成树中至少有一条边不同,则这两个最小生成树就是不同的)。由于不同的最小生成树可能很多,所以你只需要输出方案数对\(31011\)的模就可以了。

Solution

求最小生成树的个数。先跑一遍kruskal,求出每种边权在最小生成树出现了多少次。这里有一个结论,不同的最小生成树所用的边权是一一对应的。所以跑完kruskal后在dfs就好了。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;

inline int read() {
	int x = 0, flag = 1; char ch = getchar();
	while (ch > '9' || ch < '0') { if (ch == '-') flag = -1; ch = getchar(); }
	while (ch <= '9' && ch >= '0') { x = x * 10 + ch - '0'; ch = getchar(); }
	return x * flag;
}

#define N 1005
#define rep(ii, aa, bb) for (int ii = aa; ii <= bb; ii++)
#define ll long long
const ll ha = 31011;

int n, m;
int fa[N];
struct edgeType { int u, v, w; } e[N];
bool cmp(const edgeType x, const edgeType y) { return x.w < y.w; }
struct saveType { int l, r, w; } s[N];
int tot;
int sum;

int find(int x) { return x == fa[x] ? x : find(fa[x]); }

void dfs(int x, int pos, int cnt) {
	if (pos == s[x].r + 1) {
		sum += (cnt == s[x].w);
		return;
	}
	int u = find(e[pos].u), v = find(e[pos].v);
	if (u != v) {
		fa[u] = v;
		dfs(x, pos + 1, cnt + 1);
		fa[u] = u; fa[v] = v;
	}
	dfs(x, pos + 1, cnt);
}

int main() {
	cin >> n >> m;
	rep(i, 1, n) fa[i] = i;
	rep(i, 1, m) e[i].u = read(), e[i].v = read(), e[i].w = read();
	sort(e + 1, e + 1 + m, cmp);
	int cnt = 0;
	rep(i, 1, m) {
		if (e[i].w != e[i - 1].w) { s[++tot].l = i; s[tot - 1].r = i - 1; }
		int u = find(e[i].u), v = find(e[i].v);
		if (u != v) { cnt++; s[tot].w++; fa[u] = v; }
	}
	s[tot].r = m;
	if (cnt != n - 1) { putchar('0'); return 0; }
	rep(i, 1, n) fa[i] = i;
	int ans = 1;
	rep(i, 1, tot) {
		sum = 0;
		dfs(i, s[i].l, 0);
		(ans *= sum) %= ha;
		rep(j, s[i].l, s[i].r) {
			int u = find(e[j].u), v = find(e[j].v);
			if (u != v) fa[u] = v;
		}
	}
	cout << ans;
	return 0;
}
posted @ 2018-02-05 09:20  aziint  阅读(99)  评论(0编辑  收藏  举报
Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.