【HNOI2013】游走
题面
题解
图上的期望大部分是\(dp\),无向图的期望大部分是高斯消元
设\(f[i]\)表示走到点\(i\)的期望,\(d[i]\)表示\(i\)的度,\(to(i)\)表示\(i\)能到达的点集
所以\(f[i] = \sum\limits_{x \in to(i)} f[x] / d[x]\)
然后每个点能够列出这样的方程,直接高斯消元就可以了
代码
#include<bits/stdc++.h>
#define RG register
#define clear(x, y) memset(x, y, sizeof(x));
using namespace std;
inline int read()
{
int data = 0, w = 1;
char ch = getchar();
while(ch != '-' && (ch < '0' || ch > '9')) ch = getchar();
if(ch == '-') w = -1, ch = getchar();
while(ch >= '0' && ch <= '9') data = data * 10 + (ch ^ 48), ch = getchar();
return data*w;
}
const int maxn(510), maxm(250100);
struct edge { int next, to; } e[maxm << 1];
int head[maxn], e_num;
inline void add_edge(int from, int to) { e[++e_num] = {head[from], to}; head[from] = e_num; }
double a[maxn][maxn], ans[maxm], Ans, deg[maxn];
int n, m, from[maxm], to[maxm];
inline void Gauss()
{
for(RG int i = 1, k = i; i <= n; i++, k = i)
{
for(RG int j = k + 1; j <= n; j++) if(fabs(a[k][i]) < fabs(a[j][i])) k = j;
swap(a[i], a[k]);
for(RG int j = i + 1; j <= n + 1; j++) a[i][j] /= a[i][i];
a[i][i] = 1.;
for(RG int j = 1; j <= n; j++)
{
if(i == j) continue;
for(RG int k = i + 1; k <= n + 1; k++) a[j][k] -= a[j][i] * a[i][k];
a[j][i] = 0.;
}
}
}
int main()
{
n = read(); m = read();
for(RG int i = 1; i <= m; i++)
{
from[i] = read(); to[i] = read();
add_edge(from[i], to[i]); deg[from[i]] += 1.;
add_edge(to[i], from[i]); deg[to[i]] += 1.;
}
for(RG int i = 1; i < n; i++)
{
for(RG int j = head[i]; j; j = e[j].next) if(e[j].to != n) a[i][e[j].to] += -1. / deg[e[j].to];
a[i][i] = 1;
}
a[n][n] = 1;
a[1][n + 1] = 1; Gauss();
for(RG int i = 1; i <= m; i++)
ans[i] = ((from[i] == n) ? 0 : a[from[i]][n + 1] / deg[from[i]]) + ((to[i] == n) ? 0 : a[to[i]][n + 1] / deg[to[i]]);
sort(ans + 1, ans + m + 1);
for(RG int i = 1; i <= m; i++) Ans += (m - i + 1) * ans[i];
printf("%.3lf\n", Ans);
return 0;
}