BZOJ 1778: [Usaco2010 Hol]Dotp 驱逐猪猡 [高斯消元 概率DP]
1778: [Usaco2010 Hol]Dotp 驱逐猪猡
题意:一个炸弹从1出发p/q的概率爆炸,否则等概率走向相邻的点。求在每个点爆炸的概率
高斯消元求不爆炸到达每个点的概率,然后在一个点爆炸就是\(\frac{f[i]}{sum}\)
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;
typedef unsigned long long ll;
const int N=305, M=1e5;
const double eps=1e-15;
inline int read() {
char c=getchar(); int x=0, f=1;
while(c<'0' || c>'9') {if(c=='-')f=-1; c=getchar();}
while(c>='0' && c<='9') {x=x*10+c-'0'; c=getchar();}
return x*f;
}
int n, m, u, v, de[N]; double p, q;
struct edge{int v, ne;}e[M];
int cnt=1, h[N];
inline void ins(int u, int v) {
e[++cnt]=(edge){v, h[u]}; h[u]=cnt;
e[++cnt]=(edge){u, h[v]}; h[v]=cnt;
}
double a[N][N];
void build() {
a[1][1]=1; a[1][n+1]=1;
for(int u=1; u<=n; u++) {
a[u][u] = 1;
for(int i=h[u];i;i=e[i].ne) {
int v=e[i].v;
a[u][v] += -(1-p/q)/de[v];
}
}
//for(int i=1; i<=n; i++) for(int j=1; j<=n+1; j++) printf("%lf%c",a[i][j], j==n+1?'\n':' ');
}
void gauss() {
for(int i=1; i<=n; i++) {
int r=i;
for(int j=i; j<=n; j++) if(abs(a[j][i])>abs(a[r][i])) r=j;
if(r!=i) for(int j=1; j<=n+1; j++) swap(a[r][j], a[i][j]);
for(int k=i+1; k<=n; k++) if(abs(a[k][i])>eps) {
double t = a[k][i]/a[i][i];
for(int j=i; j<=n+1; j++) a[k][j] -= t*a[i][j];
}
}
for(int i=n; i>=1; i--) {
for(int j=n; j>i; j--) a[i][n+1] -= a[i][j]*a[j][n+1];
a[i][n+1] /= a[i][i];
}
}
int main() {
freopen("in","r",stdin);
n=read(); m=read(); p=read(); q=read();
for(int i=1; i<=m; i++) u=read(), v=read(), ins(u, v), de[u]++, de[v]++;
build();
gauss();
double sum=0;
for(int i=1; i<=n; i++) sum += a[i][n+1];// printf("hi %d %lf\n", i, a[i][n+1]);
for(int i=1; i<=n; i++) printf("%.9lf\n", a[i][n+1]/sum+eps);
}
Copyright:http://www.cnblogs.com/candy99/