bzoj 3143 [Hnoi2013]游走 期望dp+高斯消元
题面
解法
设\(f_i\)表示经过点\(i\)的期望次数
然后就可以通过边的关系搞出一个方程组,高斯消元一下
对于求一条边\((x,y)\)的概率,即为\(\frac{f_x}{out_x}+\frac{f_y}{out_y}\)
然后按照概率大小排序,小的用尽量大的编号
时间复杂度:\(O(n^3)\)
代码
#include <bits/stdc++.h>
#define double long double
#define eps 1e-9
#define N 510
using namespace std;
int s[N];
vector <int> e[N];
double b[N * N], a[N][N];
void gauss(int n) {
for (int i = 1; i <= n; i++) {
if (fabs(a[i][i]) < eps)
for (int j = i + 1; j <= n; j++)
if (fabs(a[j][i]) > eps)
for (int k = 1; k <= n + 1; k++) swap(a[i][k], a[j][k]);
for (int j = i + 1; j <= n + 1; j++) a[i][j] /= a[i][i];
for (int j = 1; j <= n; j++) {
if (i == j) continue;
for (int k = i + 1; k <= n + 1; k++)
a[j][k] -= a[j][i] * a[i][k];
}
}
}
int main() {
ios::sync_with_stdio(false);
int n, m; cin >> n >> m;
for (int i = 1; i <= m; i++) {
int x, y; cin >> x >> y;
s[x]++, s[y]++;
e[x].push_back(y), e[y].push_back(x);
}
for (int i = 1; i < n; i++) {
a[i][i] = 1;
for (int j = 0; j < e[i].size(); j++) {
int k = e[i][j];
if (k != n) a[i][k] -= 1.0 / s[k];
}
}
a[1][n] = 1;
gauss(n - 1); int tot = 0;
for (int i = 1; i < n; i++)
for (int j = 0; j < e[i].size(); j++) {
int k = e[i][j]; if (i > k) continue;
b[++tot] = a[i][n] / s[i] + a[k][n] / s[k];
}
sort(b + 1, b + m + 1); double ans = 0;
for (int i = 1; i <= m; i++) ans += b[i] * (m - i + 1);
cout << fixed << setprecision(3) << ans << "\n";
return 0;
}