HDU 6836 Expectation(矩阵生成树 + 期望)

Expectation

思路

题目要求每个生成树边权 & \& 的期望值,假设当前这颗生成树对二进制数的第 i i 位有贡献,则这个位上的构成生成树的边权值一定是 1 1 ,所以我们可以跑 31 31 位二进制数的,矩阵树,每个位上的贡献度等于,这个位上的生成树数量乘以这个位上的2次幂,最后再跑一边生成树计数,然后即可求得期望。

代码

/*
  Author : lifehappy
*/
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>

#define mp make_pair
#define pb push_back
#define endl '\n'
#define mid (l + r >> 1)
#define lson rt << 1, l, mid
#define rson rt << 1 | 1, mid + 1, r
#define ls rt << 1
#define rs rt << 1 | 1

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;

const double pi = acos(-1.0);
const double eps = 1e-7;
const int inf = 0x3f3f3f3f;

inline ll read() {
    ll f = 1, x = 0;
    char c = getchar();
    while(c < '0' || c > '9') {
        if(c == '-')    f = -1;
        c = getchar();
    }
    while(c >= '0' && c <= '9') {
        x = (x << 1) + (x << 3) + (c ^ 48);
        c = getchar();
    }
    return f * x;
}

ll A[110][110];

const int mod = 998244353;

ll quick_pow(ll a, ll n, ll mod) {
    ll ans = 1;
    while(n) {
        if(n & 1) ans = ans * a % mod;
        a = a * a % mod;
        n >>= 1;
    }
    return ans;
}

ll inv(ll a) {
    return quick_pow(a, mod - 2, mod);
}

ll gauss(int n){
    ll ans = 1;
    for(int i = 1; i <= n; i++){
        for(int j = i; j <= n; j++) {
            if(A[j][i]){
                for(int k = i; k <= n; k++) swap(A[i][k], A[j][k]);
                if(i != j) ans = -ans;
                break;
            }
        }
        if(!A[i][i]) return 0;
        for(ll j = i + 1, iv = inv(A[i][i]); j <= n; j++) {
                ll t = A[j][i] * iv % mod;
                for(int k = i; k <= n; k++)
                    A[j][k] = (A[j][k] - t * A[i][k] % mod + mod) % mod;
        }
        ans = (ans * A[i][i] % mod + mod) % mod;
    }
    return ans;
}

void add(int x, int y, int w) {
    (A[x][y] -= w) %= mod;
    (A[y][y] += w) %= mod;
}

const int N = 1e4 + 10;

int x[N], y[N], w[N], n, m;

int main() {
    // freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
    // ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    int T = read();
    while(T--) {
        n = read(), m = read();
        for(int i = 1; i <= m; i++) {
            x[i] = read(), y[i] = read(), w[i] = read();
        }
        ll ans = 0;
        for(int i = 0; i <= 30; i++) {
            memset(A, 0, sizeof A);
            for(int j = 1; j <= m; j++) {
                add(x[j], y[j], w[j] >> i & 1);
                add(y[j], x[j], w[j] >> i & 1);
            }
            ans = (ans + (gauss(n - 1) * (1 << i) % mod)) % mod;
        }
        memset(A, 0, sizeof A);
        for(int j = 1; j <= m; j++) {
            add(x[j], y[j], 1);
            add(y[j], x[j], 1);
        }
        ans = ans * inv(gauss(n - 1)) % mod;
        printf("%lld\n", (ans % mod + mod) % mod);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45483201/article/details/107866925