# BZOJ3143：[Hnoi2013]游走 （高斯消元+概率DP）

$f\left[i\right]=\sum _{\left(i,j\right)\in e,j\ne n}\frac{f\left[j\right]}{deg\left[j\right]}$

f[n]由于对任何值都没有贡献，直接设为0。

CODE：

#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<stdio.h>
#include<algorithm>
using namespace std;

const int maxn=510;
const long double eps=1e-10;
typedef long double LD;

LD a[maxn][maxn];
LD f[maxn];

struct data
{
int u,v;
LD g;
} e[maxn*maxn];

int deg[maxn];
int n,m;

LD Abs(LD x)
{
if (x>0.0) return x;
return -x;
}

int Gauss()
{
int R,r=1,c=1;
while ( r<=n && c<=n )
{
R=r;
for (int i=r+1; i<=n; i++)
if ( Abs(a[i][c])>Abs(a[R][c]) ) R=i;

if ( Abs(a[R][c])<=eps ) r--;
else
{
for (int j=c; j<=n+1; j++) swap(a[R][j],a[r][j]);
for (int i=r+1; i<=n; i++)
if ( Abs(a[i][c])>eps )
{
for (int j=c+1; j<=n+1; j++)
a[i][j]=a[i][j]/a[i][c]-a[r][j]/a[r][c];
a[i][c]=0.0;
}
}

r++;
c++;
}

for (int i=r; i<=n; i++)
if ( Abs(a[i][n+1])>eps ) return -1;
if (r<=n) return n-r+1;

for (int i=n; i>=1; i--)
{
for (int j=i+1; j<=n; j++) a[i][n+1]-=a[i][j]*f[j];
f[i]=a[i][n+1]/a[i][i];
}
}

bool Comp(data x,data y)
{
return x.g<y.g;
}

int main()
{
freopen("3143.in","r",stdin);
freopen("3143.out","w",stdout);

scanf("%d%d",&n,&m);
for (int i=1; i<=m; i++)
{
scanf("%d%d",&e[i].u,&e[i].v);
deg[ e[i].u ]++;
deg[ e[i].v ]++;
}

for (int i=1; i<=m; i++)
{
if (e[i].u!=n) a[ e[i].v ][ e[i].u ]=1.0/(LD)deg[ e[i].u ];
if (e[i].v!=n) a[ e[i].u ][ e[i].v ]=1.0/(LD)deg[ e[i].v ];
}
for (int i=1; i<n; i++) a[i][i]=-1.0;
a[1][n]=-1.0;

n--;
Gauss();
n++;
f[n]=1.0;

for (int i=1; i<=m; i++)
{
e[i].g=0.0;
if (e[i].u!=n) e[i].g+=f[ e[i].u ]/(LD)deg[ e[i].u ];
if (e[i].v!=n) e[i].g+=f[ e[i].v ]/(LD)deg[ e[i].v ];
}
sort(e+1,e+m+1,Comp);

LD ans=0.0;
for (int i=1; i<=m; i++) ans+=(LD)i*e[m-i+1].g;
printf("%.3Lf\n",ans);

return 0;
}

©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客