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

4 6
1 2 1
1 3 1
1 4 1
2 3 2
2 4 1
3 4 1

## Sample Output

8

——sengxian

 1 //It is made by wfj_2048~
2 #include <algorithm>
3 #include <iostream>
4 #include <complex>
5 #include <cstring>
6 #include <cstdlib>
7 #include <cstdio>
8 #include <vector>
9 #include <cmath>
10 #include <queue>
11 #include <stack>
12 #include <map>
13 #include <set>
14 #define rhl (31011)
15 #define inf (1<<30)
16 #define N (1010)
17 #define il inline
18 #define RG register
19 #define ll long long
20 #define File(s) freopen(s".in","r",stdin),freopen(s".out","w",stdout)
21
22 using namespace std;
23
24 struct edge{ int u,v,w; }g[100010];
25 struct node{ int l,r; }a[100010];
26
27 int fa[100010],sum[100010],n,m,k,cnt,res,ans;
28
29 il int gi(){
30     RG int x=0,q=1; RG char ch=getchar(); while ((ch<'0' || ch>'9') && ch!='-') ch=getchar();
31     if (ch=='-') q=-1,ch=getchar(); while (ch>='0' && ch<='9') x=x*10+ch-48,ch=getchar(); return q*x;
32 }
33
34 il int cmp(const edge &a,const edge &b){ return a.w<b.w; }
35
36 il int find(RG int x){ return fa[x]==x ? fa[x] : find(fa[x]); }
37
38 il void dfs(RG int cnt,RG int x,RG int v){
39     if (x>a[cnt].r){ if (v==sum[cnt]) res++; return; }
40     dfs(cnt,x+1,v); RG int p=find(g[x].u),q=find(g[x].v);
41     if (p!=q) fa[p]=q,dfs(cnt,x+1,v+1),fa[p]=p,fa[q]=q;
42     return;
43 }
44
45 il void work(){
46     n=gi(),m=gi();
47     for (RG int i=1;i<=m;++i) g[i].u=gi(),g[i].v=gi(),g[i].w=gi();
48     sort(g+1,g+m+1,cmp); for (RG int i=1;i<=n;++i) fa[i]=i; cnt=0;
49     for (RG int i=1;i<=m;++i){
50     if (g[i].w!=g[i-1].w) cnt++;
51     if (!a[cnt].l) a[cnt].l=i; a[cnt].r=i;
52     RG int p=find(g[i].u),q=find(g[i].v);
53     if (p!=q) fa[p]=q,k++,sum[cnt]++;
54     }
55     if (k!=n-1){ printf("0"); return; }
56     for (RG int i=1;i<=n;++i) fa[i]=i; ans=1;
57     for (RG int i=1;i<=cnt;++i){
58     res=0,dfs(i,a[i].l,0),(ans*=res)%=rhl;
59     for (RG int j=a[i].l;j<=a[i].r;++j){
60         int p=find(g[j].u),q=find(g[j].v);
61         if (p!=q) fa[p]=q;
62     }
63     }
64     printf("%d",ans); return;
65 }
66
67 int main(){
68     File("counttree");
69     work();
70     return 0;
71 }

posted @ 2017-03-18 18:57  wfj_2048  阅读(151)  评论(0编辑  收藏