中文题目,猫抓老鼠的故事,老鼠的移动是等概率的随机移动,而猫会选择离老鼠最近的标号最小的点的走,依次移动猫若没有抓到老鼠,可以再移动一步,求猫抓到老鼠的步数期望值。
首先需要处理的是老鼠在任意点x时,猫在任意点y时,猫的移动策略。用nex[i][j]表示猫在i点,老鼠在j点时,猫下一步应该移动的位置,对每一个点进行依次广搜即可求出,dp[i][j]表示猫在i点,老鼠在j点时猫抓到老鼠的步数期望值,对于每一轮移动,若猫和老鼠已经再同一个点了,则这轮的期望为0,若猫再走一步或者两步就能抓到老鼠,则这轮的期望为1,否则这轮抓不到老鼠,枚举老鼠往周围每一个方向移动的下一轮,递归记忆化搜索。(老鼠还有概率不移动,也要计算进去)。
#include<iostream>
#include<algorithm>
#include<string.h>
#include<stdio.h>
#include<vector>
#include<string>
#include<queue>
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
const int maxe = 30005;
const int maxk = 505;
const int mod = 1000000000;
const int maxn = 1005;
int n, m;
int beg, endd;
double f[maxn][maxn];
vector<int> e[maxn];
bool vis[maxn][maxn];
queue<pair<int, int> >que;
int nex[maxn][maxn];
void bfs(int cnt){
bool v[maxn] = { 0 };
que.push({ cnt, 0 });
while (!que.empty()){
pair<int, int> cur = que.front();
que.pop();
for (int i = 0; i < e[cur.first].size(); i++){
if (v[e[cur.first][i]])continue;
v[e[cur.first][i]] = 1;
int f;
if (cur.first == cnt)f = e[cur.first][i];
else f = cur.second;
que.push({ e[cur.first][i], f });
nex[cnt][e[cur.first][i]] = f;
}
}
}
double dp(int from, int to){
if (vis[from][to])return f[from][to];
vis[from][to] = 1;
if (from == to)return f[from][to] = 0;
int p = nex[from][to];
if (p == to || nex[p][to] == to)return f[from][to] = 1;
f[from][to] = 0;
for (int i = 0; i < e[to].size(); i++){
f[from][to] += dp(nex[p][to], e[to][i]);
}
f[from][to] += dp(nex[p][to], to);
f[from][to] /= (e[to].size() + 1);
f[from][to]++;
return f[from][to];
}
int main(){
int x, y;
scanf("%d%d", &n, &m);
scanf("%d%d", &beg, &endd);
for (int i = 0; i < m; i++){
scanf("%d%d", &x, &y);
e[x].push_back(y);
e[y].push_back(x);
}
for (int i = 1; i <= n; i++){
sort(e[i].begin(), e[i].end());
bfs(i);
}
memset(vis, 0, sizeof(vis));
printf("%.3lf\n", dp(beg, endd));
return 0;
}