【BZOJ1016】[JSOI2008]最小生成树计数【最小生成树】【搜索】

【题目链接】

参考了【hzwer的题解】orz

要利用最小生成树的性质:对于所有的最小生成树,边权相等的边出现次数都相同。

/* Footprints In The Blood Soaked Snow */
#include <cstdio>
#include <algorithm>

using namespace std;

const int maxn = 105, maxm = 1005, p = 31011;

int n, m, fa[maxn], tot, sum, ans;

struct _edge {
	int u, v, w;
} g[maxm];

struct _data {
	int cnt, l, r;
} e[maxm];

inline int iread() {
	int f = 1, x = 0; char ch = getchar();
	for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1;
	for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
	return f * x;
}

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

inline bool cmp(_edge a, _edge b) {
	return a.w < b.w;
}

inline void dfs(int now, int id, int used) {
	if(now == e[id].r + 1) {
		if(used == e[id].cnt) sum++;
		return;
	}
	int u = find(g[now].u), v = find(g[now].v);
	if(u != v) {
		fa[u] = v;
		dfs(now + 1, id, used + 1);
		fa[u] = u; fa[v] = v;
	}
	dfs(now + 1, id, used);
}

int main() {
	n = iread(); m = iread();
	for(int i = 1; i <= m; i++) {
		int u = iread(), v = iread(), w = iread();
		g[i] = (_edge){u, v, w};
	}

	for(int i = 1; i <= n; i++) fa[i] = i;
	sort(g + 1, g + 1 + m, cmp);

	int flag = 0;
	for(int i = 1; i <= m; i++) {
		if(g[i - 1].w != g[i].w) {
			e[tot].r = i - 1; ++tot;
			e[tot].l = i;
		}
		int u = find(g[i].u), v = find(g[i].v);
		if(u != v) {
			e[tot].cnt++;
			fa[u] = v;
			flag++;
		}
	}
	e[tot].r = m;

	if(flag != n - 1) {
		printf("0\n");
		return 0;
	}

	for(int i = 1; i <= n; i++) fa[i] = i;
	ans = 1;
	for(int i = 1; i <= tot; i++) {
		if(e[i].cnt) {
			sum = 0;
			dfs(e[i].l, i, 0);
		} else sum = 1;
		ans = ans * sum % p;
		for(int j = e[i].l; j <= e[i].r; j++) {
			int u = find(g[j].u), v = find(g[j].v);
			fa[u] = v;
		}
	}

	printf("%d\n", ans);
	return 0;
}


你可能感兴趣的:(最小生成树)