# bzoj1016 [JSOI2008]最小生成树计数

### Solution

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

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;
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  阅读(54)  评论(0编辑  收藏