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

时空隧道


分析:
我们首先考虑怎么求最小生成树—kruskal
sort之后贪心
现在我们把w相同的边看成一个集合,所有的最小生成树中每个集合的选择的边的数目是一定的,每个集合对于图的连通性的贡献也是一定的,所以我们可以dfs求出每个集合的合法方案,然后乘法原理就好了
那么怎么dfs呢
暴力枚举啦…


代码如下:

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int maxn=100+5,maxm=1000+5,MOD=31011;
int n,m,fa[maxn],tot,cnt,sum,ans;
struct M{
    int x,y,w;
    friend bool operator < (M a,M b){
        return a.w<b.w;
    }
}s[maxm],l[maxm];
inline int find(int x){
    return fa[x]==x?x:find(fa[x]);
}
inline void kruskal(void){
    tot=cnt=0;
    sort(s+1,s+m+1);
    for(int i=1;i<=m;i++){
        if(s[i].w!=s[i-1].w)
            l[cnt].y=i-1,l[++cnt].x=i;
        if(find(s[i].x)!=find(s[i].y))
            fa[find(s[i].x)]=find(s[i].y),l[cnt].w++,tot++;
    }
    l[cnt].y=m;
}
inline void dfs(int id,int num,int lala){
    //cout<<"num: "<<num<<endl;
    if(num==l[id].y+1){
//      cout<<"lala"<<endl;
        if(lala==l[id].w+1)
            /*cout<<sum<<endl,*/sum++;
        return;
    }
    int xx=find(s[num].x),yy=find(s[num].y);
    if(xx!=yy)
        /*cout<<num<<" "<<xx<<" "<<yy<<endl,*/fa[xx]=yy,dfs(id,num+1,lala+1),fa[xx]=xx;
    dfs(id,num+1,lala);
}
signed main(void){
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
        fa[i]=i;
    for(int i=1;i<=m;i++)
        scanf("%d%d%d",&s[i].x,&s[i].y,&s[i].w);
    kruskal();
    if(tot!=n-1){
        puts("0");
        return 0;
    }
    ans=1;
    for(int i=1;i<=n;i++)
        fa[i]=i;
    for(int i=1;i<=cnt;i++){
        sum=0,dfs(i,l[i].x,1);
        ans=(ans*sum)%MOD;
        for(int j=l[i].x;j<=l[i].y;j++)
            if(find(s[j].x)!=find(s[j].y))
                fa[find(s[j].x)]=find(s[j].y);
    }
    cout<<ans<<endl;
    return 0;
}

by >_< NeighThorn

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值