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

时间:2021-09-13 15:48:19

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

 #include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<ctime>
using namespace std;
#define mod 31011
int n,m,len,sum,tot,ans=,f[];
struct node{int x,y,v;}e[];
struct sha{int l,r,v;}a[];
bool cmp(node a,node b) {return a.v<b.v;}
int find(int x) {return f[x]==x?x:find(f[x]);}
namespace INIT
{
char buf[<<],*fs,*ft;
inline char getc() {return (fs==ft&&(ft=(fs=buf)+fread(buf,,<<,stdin),fs==ft))?:*fs++;}
inline int read()
{
int x=,f=; char ch=getc();
while(!isdigit(ch)) {if(ch=='-') f=-; ch=getc();}
while(isdigit(ch)) {x=x*+ch-''; ch=getc();}
return x*f;
}
}using namespace INIT;
void dfs(int x,int now,int k)
{
if(now==a[x].r+)
{
if(k==a[x].v) sum++;
return;
}
int p=find(e[now].x),q=find(e[now].y);
if(p!=q)
{
f[p]=q;
dfs(x,now+,k+);
f[p]=p; f[q]=q;
}
dfs(x,now+,k);
}
int main()
{
//freopen("cin.in","r",stdin);
//freopen("cout.out","w",stdout);
n=read(); m=read();
for(int i=;i<=n;i++) f[i]=i;
for(int i=;i<=m;i++) e[i].x=read(),e[i].y=read(),e[i].v=read();
sort(e+,e+m+,cmp);
for(int i=;i<=m;i++)
{
if(e[i].v!=e[i-].v) {a[++len].l=i;a[len-].r=i-;}
int p=find(e[i].x),q=find(e[i].y);
if(p!=q) {f[p]=q; a[len].v++; tot++;}
}
a[len].r=m;
if(tot!=n-) {printf("0\n"); return ;}
for(int i=;i<=n;i++) f[i]=i;
for(int i=;i<=len;i++)
{
sum=;
dfs(i,a[i].l,);
ans=(ans*sum)%mod;
for(int j=a[i].l;j<=a[i].r;j++)
{
int p=find(e[j].x),q=find(e[j].y);
if(p!=q) f[p]=q;
}
}
printf("%d\n",ans);
return ;
}