题意:LL从起点’@’出发,在每个点等概率的向可以走的点走。’$’是目的地,可能有多个。问从起点到目的地走的步数的期望?
思路:每个点
假设E1E2...Ek为Ei周围的点的期望
Ei=(E1+E2+...+Ek)/k+1
E1+E2+...+Ek−k∗Ei=−k
列出方程,用高斯消元法去解
注意:要用BFS或者DFS的方法去找点,因为如果你的高斯消元是要求出每个
Ei
的话,
@..#...#$
上面这个例子,右上角的点是解不出来的,就会导致答案出现错误。
http://acm.hdu.edu.cn/showproblem.php?pid=2262
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <cmath>
#include <ctime>
#include <cstdio>
#include <vector>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#define rep(i,a,b) for(int i = (a) ; i <= (b) ; i ++)
#define rrep(i,a,b) for(int i = (b) ; i >= (a) ; i --)
#define repS(it,p) for(auto it = p.begin() ; it != p.end() ; it ++)
#define repE(p,u) for(Edge * p = G[u].first ; p ; p = p -> next)
#define cls(a,x) memset(a,x,sizeof(a))
#define eps 1e-8
using namespace std;
const int MOD = 1e9+7;
const int INF = 0x3f3f3f3f;
const int MAXN = 255;
const int MAXE = 2e5+5;
typedef long long LL;
typedef unsigned long long ULL;
int T,n,m;
int fx[] = {0,1,-1,0,0};
int fy[] = {0,0,0,-1,1};
double a[MAXN][MAXN],x[MAXN];
int equ ;
char Map[20][20];
bool vis[20][20];
int idx[20][20];
struct qnode {
int x,y;
qnode(int _x,int _y) {x = _x ; y = _y;}
};
queue<qnode>que;
void debug() {
rep(i,1,equ) {
rep(j,1,equ) {
printf("%f ",a[i][j]);
}
printf("= %f\n",x[i]);
}
puts("");
}
bool gauss() {
rep(i,1,equ) {
int maxd = i;
rep(j,i+1,equ) if(fabs(a[maxd][i])<fabs(a[j][i])) maxd = j;
if(fabs(a[maxd][i])<eps) return false;
if(maxd != i) {
rep(j,i,equ) swap(a[maxd][j],a[i][j]);
swap(x[maxd],x[i]);
}
rep(j,i+1,equ) {
double rate = a[j][i] / a[i][i];
rep(k,i,equ) {
a[j][k] -= rate * a[i][k];
}
x[j] -= rate * x[i];
}
}
rrep(i,1,equ) {
rep(j,i+1,equ) {
x[i] -= a[i][j] * x[j];
}
x[i] /= a[i][i];
}
return true;
}
void input() {
rep(i,1,n) scanf("%s",&Map[i][1]);
}
int tot ;
int index ;
int sx,sy;
int BFS() {
while(!que.empty()) que.pop();
que.push(qnode(sx,sy));
cls(vis,0);
index = 0;
vis[sx][sy] = 1; idx[sx][sy] = ++index;
tot = 0;
while(!que.empty()) {
qnode tmp = que.front();
que.pop();
++ tot;
int cnt = 0;
if(Map[tmp.x][tmp.y] == '$') {
a[tot][idx[tmp.x][tmp.y]] = 1;
x[tot] = 0;
continue;
}
rep(i,1,4) {
int tmpx = tmp.x + fx[i];
int tmpy = tmp.y + fy[i];
if(tmpx >= 1 && tmpx <= n && tmpy >= 1 && tmpy <= m && Map[tmpx][tmpy] != '#') {
if(!vis[tmpx][tmpy]) {
vis[tmpx][tmpy] = 1;
idx[tmpx][tmpy] = ++index;
que.push(qnode(tmpx,tmpy));
}
cnt ++;
a[tot][idx[tmpx][tmpy]] = 1;
}
}
a[tot][idx[tmp.x][tmp.y]] = -cnt;
x[tot] = - cnt;
}
return tot;
}
void solve() {
cls(a,0);
rep(i,1,n) rep(j,1,m) {
if(Map[i][j] == '@') {
sx = i; sy = j;
}
}
BFS();
equ = tot;
if(!gauss()) puts("-1");
else printf("%.6f\n",x[1]);
}
int main(void) {
while(~scanf("%d %d",&n,&m)) {
input();
solve();
}
return 0;
}