[BZOJ3143][HNOI2013]游走(高斯消元解期望方程)

可以假设,如果知道了每一条边的期望经过次数 w(u,v) ,就可以排序后贪心分配了。以下 du 为节点 u 的度。
fu为节点 u 的期望经过次数,则容易得到:
w(u,v)=fudu+fvdv
那么怎样求 fu 呢?
简单的一个想法,设 v 为与u相邻的点集:
fu=fvdv
但是注意下面两个特殊条件:
1、第 1 个节点一开始就已经经过了。所以f1的转移应该为 f1=1+fvdv
2、走到第 N 个节点就走出去了,所以任意一个点都不能从N转移,计算 w 时也不可以将fNdN计入答案。所以这时候要把 fN 设为 0 ,而不是1
把上面的方程移项后高斯消元即可求出。
代码:

#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
inline int read() {
    int res = 0; bool bo = 0; char c;
    while (((c = getchar()) < '0' || c > '9') && c != '-');
    if (c == '-') bo = 1; else res = c - 48;
    while ((c = getchar()) >= '0' && c <= '9')
        res = (res << 3) + (res << 1) + (c - 48);
    return bo ? ~res + 1 : res;
}
const int N = 505, M = 3e5 + 5;
int n, m, ecnt, nxt[M], adj[N], st[M], go[M], cnt[N];
double d[N], a[N][N], ans[M];
inline void add_edge(const int u, const int v) {
    nxt[++ecnt] = adj[u]; adj[u] = ecnt; st[ecnt] = u; go[ecnt] = v;
    if (u != v) nxt[++ecnt] = adj[v], adj[v] = ecnt, st[ecnt] = v, go[ecnt] = u;
    cnt[u]++; if (u != v) cnt[v]++;
}
void Gauss() {
    int i, j, k;
    for (i = 1; i <= n; i++) {
        int u = i;
        for (j = i + 1; j <= n; j++)
            if (fabs(a[j][i]) > fabs(a[u][i])) u = j;
        if (u != i) for (j = i; j <= n + 1; j++)
            swap(a[i][j], a[u][j]);
        double tmp = a[i][i];
        for (j = i; j <= n + 1; j++) a[i][j] /= tmp;
        for (j = 1; j <= n; j++) if (j != i) {
            tmp = a[j][i];
            for (k = i; k <= n + 1; k++)
                a[j][k] -= a[i][k] * tmp;
        }
    }
}
double solve() {
    int i, u; a[1][n + 1] = a[n][n] = 1;
    for (u = 1; u < n; u++) {
        a[u][u] = 1;
        for (int e = adj[u], v; e; e = nxt[e])
            a[u][v = go[e]] -= d[v];
    }
    Gauss(); for (i = 1; i <= ecnt; i += 2) {
        int x = st[i], y = go[i];
        ans[(i >> 1) + 1] = a[x][n + 1] * d[x]
            + a[y][n + 1] * d[y];
    }
    sort(ans + 1, ans + m + 1); double res = 0;
    for (i = 1; i <= m; i++) res += ans[i] * (m - i + 1);
    return res;
}
int main() {
    int i, x, y; n = read(); m = read();
    for (i = 1; i <= m; i++) x = read(), y = read(),
        add_edge(x, y); for (i = 1; i <= n; i++)
        d[i] = 1.0 / cnt[i]; printf("%.3lf\n", solve());
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值