HDU多校6 - 6836 Expectation(矩阵树定理+高斯消元求行列式)

题目链接:点击查看

题目大意:给出一张由 n 个点和 m 条边组成的无向图,对于任意一个生成树,其权值为 n - 1 条边的边权进行二进制的 and 运算,现在需要在图中任意选择一个生成树,问期望权值是多少

题目分析:需要对题意进行转换,根据期望的公式 E( aX + bY ) = aE( X ) + bE( Y ) ,又因为 and 运算对于每一位都是相互独立的,所以拆位然后单独讨论

首先求出来 sum 为原图中有多少个生成树,对于二进制的每一位 i 来说,令所有第 i 位为 1 的边建图,对于这张新图的每一个生成树,对答案的贡献就是 \frac{2^i}{sum},累加起来就好了

关于无向图中生成树的计数问题,可以借助矩阵树定理求解

代码:
 

#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
#include<cassert>
#include<bitset>
#include<unordered_map>
using namespace std;

typedef long long LL;

typedef unsigned long long ull;

const int inf=0x3f3f3f3f;

const int N=110;

const int mod=998244353;

struct Edge
{
    int u,v,w;
}edge[N*N];

int n,m;

LL a[N][N];

LL q_pow(LL a,LL b)
{
    LL ans=1;
    while(b)
    {
        if(b&1)
            ans=ans*a%mod;
        a=a*a%mod;
        b>>=1;
    }
    return ans;
}

LL Gauss(int n)
{
    LL ans=1;
    for(int i=2;i<=n;i++)
    {
        for(int j=i+1;j<=n;j++)
            if(!a[i][i]&&a[j][i]) 
            {
                ans=-ans;
                swap(a[i],a[j]);
                break;
            }
        LL inv=q_pow(a[i][i],mod-2);
        for(int j=i+1;j<=n;j++)
        {
            LL temp=a[j][i]*inv%mod;
            for(int k=i;k<=n;k++)
                a[j][k]=(a[j][k]-a[i][k]*temp%mod+mod)%mod;
        }
        ans=ans*a[i][i]%mod;
    }
    return ans;
}

LL cal(int bit)
{
    memset(a,0,sizeof(a));
    for(int i=1;i<=m;i++)
    {
        if(bit==-1||(edge[i].w>>bit)&1)
        {
            int x=edge[i].u,y=edge[i].v;
            a[x][x]=(a[x][x]+1)%mod;
            a[y][y]=(a[y][y]+1)%mod;
            a[x][y]=(a[x][y]-1+mod)%mod;
            a[y][x]=(a[y][x]-1+mod)%mod;
        }
    }
    return Gauss(n);
}

int main()
{
#ifndef ONLINE_JUDGE
//  freopen("data.in.txt","r",stdin);
//  freopen("data.out.txt","w",stdout);
#endif
//  ios::sync_with_stdio(false);
    int w;
    cin>>w;
    while(w--)
    {
        scanf("%d%d",&n,&m);
        for(int i=1;i<=m;i++)
            scanf("%d%d%d",&edge[i].u,&edge[i].v,&edge[i].w);
        LL sum=q_pow(cal(-1),mod-2);
        LL ans=0;
        for(int i=0;i<=30;i++)
            ans=(ans+cal(i)*sum%mod*(1<<i)%mod)%mod;
        printf("%lld\n",ans);
    }


















    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_45458915/article/details/107853692