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

来源:互联网 发布:wix 建站系统源码下载 编辑:程序博客网 时间:2024/05/17 09:23

可以假设,如果知道了每一条边的期望经过次数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;}
原创粉丝点击