【bzoj1016】[JSOI2008]最小生成树计数

1016: [JSOI2008]最小生成树计数

Time Limit: 1 Sec  Memory Limit: 162 MB
Submit: 4863  Solved: 1973
[Submit][Status][Discuss]

Description

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

Input

  第一行包含两个数,n和m,其中1<=n<=100; 1<=m<=1000; 表示该无向图的节点数和边数。每个节点用1~n的整
数编号。接下来的m行,每行包含两个整数:a, b, c,表示节点a, b之间的边的权值为c,其中1<=c<=1,000,000,0
00。数据保证不会出现自回边和重边。注意:具有相同权值的边不会超过10条。

Output

  输出不同的最小生成树有多少个。你只需要输出数量对31011的模就可以了。

Sample Input

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

Sample Output

8
 
 
 
【题解】

就是不同的最小生成树方案,每种权值的边的数量是确定的,每种权值的边的作用是确定的

排序以后先做一遍最小生成树,得出每种权值的边使用的数量x

然后对于每一种权值的边搜索,得出每一种权值的边选择方案

然后乘法原理

转自——hzwer.com

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<cstdlib>
 5 #include<algorithm>
 6 #include<cmath>
 7 #include<ctime>
 8 using namespace std;
 9 #define mod 31011
10 int n,m,len,sum,tot,ans=1,f[2010];
11 struct node{int x,y,v;}e[2010];
12 struct sha{int l,r,v;}a[2010];
13 bool cmp(node a,node b)  {return a.v<b.v;}
14 int find(int x)  {return f[x]==x?x:find(f[x]);}
15 namespace INIT
16 {
17     char buf[1<<15],*fs,*ft;
18     inline char getc()  {return (fs==ft&&(ft=(fs=buf)+fread(buf,1,1<<15,stdin),fs==ft))?0:*fs++;}
19     inline int read()
20     {
21         int x=0,f=1;  char ch=getc();
22         while(!isdigit(ch))  {if(ch=='-')  f=-1;  ch=getc();}
23         while(isdigit(ch))  {x=x*10+ch-'0'; ch=getc();}
24         return x*f;
25     }
26 }using namespace INIT;
27 void dfs(int x,int now,int k)
28 {
29     if(now==a[x].r+1)
30     {
31         if(k==a[x].v)  sum++;
32         return;
33     }
34     int p=find(e[now].x),q=find(e[now].y);
35     if(p!=q)
36     {
37         f[p]=q;
38         dfs(x,now+1,k+1);
39         f[p]=p;  f[q]=q;
40     }
41     dfs(x,now+1,k);
42 }
43 int main()
44 {
45     //freopen("cin.in","r",stdin);
46     //freopen("cout.out","w",stdout);
47     n=read();  m=read();
48     for(int i=1;i<=n;i++)  f[i]=i;
49     for(int i=1;i<=m;i++)  e[i].x=read(),e[i].y=read(),e[i].v=read();
50     sort(e+1,e+m+1,cmp);
51     for(int i=1;i<=m;i++)
52     {
53         if(e[i].v!=e[i-1].v)  {a[++len].l=i;a[len-1].r=i-1;}
54         int p=find(e[i].x),q=find(e[i].y);
55         if(p!=q)  {f[p]=q; a[len].v++;  tot++;}
56     }
57     a[len].r=m;
58     if(tot!=n-1)  {printf("0\n");  return 0;}
59     for(int i=1;i<=n;i++)  f[i]=i;
60     for(int i=1;i<=len;i++)
61     {
62         sum=0;
63         dfs(i,a[i].l,0);
64         ans=(ans*sum)%mod;
65         for(int j=a[i].l;j<=a[i].r;j++)
66         {
67             int p=find(e[j].x),q=find(e[j].y);
68             if(p!=q)  f[p]=q;
69         }
70     }
71     printf("%d\n",ans);
72     return 0;
73 }

 

posted @ 2016-09-18 15:24  chty  阅读(192)  评论(0编辑  收藏  举报