1016: [JSOI2008]最小生成树计数
Time Limit: 1 Sec Memory Limit: 162 MB
Submit: 3620 Solved: 1443
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,000。数据保证不会出现自回边和重边。注意:具有相同权值的边不会超过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
题解:
先做一遍kruskal,统计一下每种权值的边用了几条,然后直接暴力枚举每种权值的边,乘法原理统计一下就好了。
ps:路径压缩的并查集回溯起来非常蛋疼,建议写不用路压的。
Code:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
#define N 110
#define M 1010
#define p 31011
struct E{
int u,v,k;
}a[M],e[M];
int n,m,num=0,ans=1,ss,head[N],fa[N];
int in(){
int x=0; char ch=getchar();
while (ch<'0' || ch>'9') ch=getchar();
while (ch>='0' && ch<='9') x=x*10+ch-'0',ch=getchar();
return x;
}
bool cmp(E x,E y){
return x.k<y.k;
}
int find(int x){
if (fa[x]!=x) return find(fa[x]);
return fa[x];
}
void kruskal(){
for (int i=1; i<=n; i++) fa[i]=i;
sort(e+1,e+m+1,cmp); int tot=0;
for (int i=1; i<=m; i++){
if (e[i].k!=e[i-1].k)
a[num].v=i-1,a[++num].u=i;
int f1=find(e[i].u),f2=find(e[i].v);
if (f1!=f2) fa[f1]=f2,tot++,a[num].k++;
}
a[num].v=m;
if (tot!=n-1){
printf("0\n");
exit(0);
}
}
void dfs(int xu,int x,int s){
if (x==a[xu].v+1){
if (s==a[xu].k) ss++;
return;
}
int f1=find(e[x].u),f2=find(e[x].v);
if (f1!=f2){
fa[f1]=f2; dfs(xu,x+1,s+1);
fa[f1]=f1,fa[f2]=f2;
}
dfs(xu,x+1,s);
}
void work(){
for (int i=1; i<=n; i++) fa[i]=i;
for (int i=1; i<=num; i++){
ss=0; dfs(i,a[i].u,0);
ans=(ans*ss)%p;
if (!ans) break;
for (int j=a[i].u; j<=a[i].v; j++){
int f1=find(e[j].u),f2=find(e[j].v);
if (f1!=f2) fa[f1]=f2;
}
}
}
int main(){
n=in(),m=in();
for (int i=1; i<=m; i++)
e[i].u=in(),e[i].v=in(),e[i].k=in();
kruskal(); work();
printf("%d\n",ans);
return 0;
}