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

【题目描述】

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

HINT

Source

【题解】

    每一种最小生成树取的每种大小的边的数量都是固定的,且每一个大小的边构建的连通性也是一样的。

    所以可以每一种边枚举取哪些,不同大小的边互不影响所以可以分开算,乘法原理统计答案即可。

/* --------------
    user Vanisher
    problem bzoj-1016
----------------*/
# include <bits/stdc++.h>
# define 	N 		200010
# define 	P 		31011
using namespace std;
struct node{
	int u,v,w;
}r[N];
int n,m,f[N],now,num,pl,pr,cnt[N],les,ans,use[N];
int read(){
	int tmp=0, fh=1; char ch=getchar();
    while (ch<'0'||ch>'9'){if (ch=='-') fh=-1; ch=getchar();}
    while (ch>='0'&&ch<='9'){tmp=tmp*10+ch-'0'; ch=getchar();}
    return tmp*fh;
}
bool cmp(node x, node y){
	return x.w<y.w;
}
int dad(int x){
	if (f[x]==x) return x;
		else return f[x]=dad(f[x]);
}
int getdad(int x){
	if (f[x]==x) return x;
		else return getdad(f[x]);
}
void dfs(int x, int tot, int k, int w){
	if (k==tot){
		now++;
		return;
	}
	if (r[x].w!=w) return;
	int u=getdad(r[x].u), v=getdad(r[x].v);
	if (u!=v){
		f[u]=v;
		dfs(x+1,tot,k+1,w);
		f[u]=u; f[v]=v;
	} 
	dfs(x+1,tot,k,w);
}
void combi(int x, int tot, int k, int w){
	if (r[x].w!=w) return;
	int u=dad(r[x].u), v=dad(r[x].v);
	if (u!=v){
		f[u]=v;
		combi(x+1,tot,k+1,w);
	} 
	else combi(x+1,tot,k,w);
}
int main(){
	n=read(), m=read();
	for (int i=1; i<=m; i++)
		r[i].u=read(), r[i].v=read(), r[i].w=read();
	for (int i=1; i<=n; i++) f[i]=i;
	sort(r+1,r+m+1,cmp);
	int las=r[1].w,k=1; r[1].w=k;
	for (int i=2; i<=m; i++){
		if (r[i].w==las)
			r[i].w=k;
			else las=r[i].w,r[i].w=++k;
	}
	for (int i=1; i<=m; i++){
		now=r[i].w;
		int u=dad(r[i].u), v=dad(r[i].v);
		if (u==v) continue;
		if (u>v) swap(u,v);
		f[v]=u; num++; use[r[i].w]++;
		if (num==n-1) break; 
	}
	if (num!=n-1){
		printf("%d\n",0);
		return 0;
	}
	for (int i=1; i<=n; i++) 	f[i]=i;
	int ans=1,l=1;
	for (int i=1; i<=r[m].w; i++){
		if (use[i]==0) continue;
		now=0;
		while (r[l].w<i) l++;
		dfs(l,use[i],0,i);
		combi(l,use[i],0,i);
		ans=ans*now%P;
	}
	printf("%d\n",ans);
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值