BZOJ1016 [JSOI2008]最小生成树计数

Code:(状态压缩)

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

#define N 110
int n, m;
struct Edge {
int f, t, len;
scanf("%d%d%d", &f, &t, &len);
}
bool operator < (const Edge &B) const {
return len < B.len;
}
}E[1010];

map<int, int> M;

int root[N], tmp[N];
void reset() {
for(int i = 1; i <= n; ++i)
root[i] = i;
}
int find(int x) {
int q = x, tq;
for(; x != root[x]; x = root[x]);
while(q != x) {
tq = root[q];
root[q] = x;
q = tq;
}
return x;
}

int count(int x) {
int res = 0;
for(; x; x -= x & -x)
++res;
return res;
}

int _debug(int x) {
return M[x];
}

#define Mod 31011
int main() {
scanf("%d%d", &n, &m);

register int i, j, k;
for(i = 1; i <= m; ++i)

sort(E + 1, E + m + 1);

int intree = 0, ra, rb;
reset();
for(i = 1; i <= m; ++i) {
ra = find(E[i].f);
rb = find(E[i].t);
if (ra != rb) {
++M[E[i].len];
root[ra] = rb;
if (++intree == n - 1)
break;
}
}

if (intree < n - 1) {
puts("0");
return 0;
}

int S, res = 1, now;
reset();
for(i = 1; i <= m; ) {
for(j = i; E[j].len == E[j + 1].len; ++j);
if (M[E[i].len]) {
memcpy(tmp, root, sizeof root);
now = 0;
for(S = 1; S < (1 << (j - i + 1)); ++S) {
if (count(S) != M[E[i].len])
continue;
memcpy(root, tmp, sizeof tmp);
bool ac = 1;
for(k = i; k <= j; ++k) {
if ((S >> (k - i)) & 1) {
ra = find(E[k].f);
rb = find(E[k].t);
if (ra == rb) {
ac = 0;
break;
}
root[ra] = rb;
}
}
if (ac)
++now;
}
res = res * now % Mod;
memcpy(root, tmp, sizeof tmp);
for(k = i; k <= j; ++k) {
ra = find(E[k].f);
rb = find(E[k].t);
if (ra != rb)
root[ra] = rb;
}
}
i = j + 1;
}

printf("%d", res);

return 0;
}

posted @ 2017-08-16 17:17  clnchanpin  阅读(...)  评论(... 编辑 收藏