猫抓老鼠的概率
【题目描述】
有这样一个游戏:在一个 n*n 的格子棋盘里,n 是奇数;有两种棋子,一个是只
能横向移动的棋子猫,一个是可以上下左右移动的棋子老鼠。假设老鼠在棋盘的正
中央,第一步老鼠将进行上下左右的随机移动。棋子猫在从棋盘的中间行的最左边
向棋盘的最右边移动,棋子猫每次移动只能是从左到右移动一步,第一步是猫位于
棋盘的中间行的最左边格子。请问:在猫移动到棋盘外面前,会有多大概率抓到老
鼠?
【输入格式】
输入一个大于 1 的奇数 n,表示棋盘的大小。
【输出格式】
棋子猫抓到棋子老鼠的概率。(小数四舍五入保留 4 位有效数字)
【样例输入】(测试数据不包含本样例)
3
【样例输出】
0.6667
输入
每一行整数N,表示环形路上N个点
第二行N个整数,用空格间隔,表示每个点上豆子颗数。
输出
一个整数,表示可以捡起的豆子数量的最大值
样例输入
3
2 3 2
样例输出
5
result:
#include<iostream>
#include<vector>
using namespace std;
vector<int> finList(vector<int> v,int index)
{
vector<int> temp=v;
for (int i=index;i<v.size();++i)
{
temp[i - index] = v[i];
}
for (int j = 0; j < index; ++j)
{
temp[v.size()-index+j] = v[j];
}
return temp;
}
int _slove(vector<int> v)
{
int sum = 0;
for (int i=0;i<v.size();++i)
{
sum += v[i];
if (v[i] % 2 != 0)
i++;
else
i = i + 2;
}
return sum;
}
int main()
{
int N, res=0;
vector<int> v,temp2;
cin >> N;
for (int i = 0; i < N; ++i)
{
int temp;
cin >> temp;
v.push_back(temp);
}
for (int i=0;i<v.size();++i)
{
int temp3;
temp2 = finList(v,i);
temp3 = _slove(temp2);
res = (res>temp3?res:temp3);
}
cout << res;
return 0;
}
这是在网友提醒之下改正后的答案,应该可以了(没有优化)
#include <iostream>
#include <iomanip>
using namespace std;
#define MOUSE 1
#define CAT -1
float calcp(int n, int x, int y, int catx, float currp, int turn)
{
if (catx == n) return 0.0;
if (catx == x && y == n / 2) return currp;
int td = 4;
if (x == 0 || x == n - 1) td--;
if (y == 0 || y == n - 1) td--;
float res = 0.0;
if (turn == MOUSE)
{
if (x != 0)
res += calcp(n, x - 1, y, catx, currp / td, turn * -1);
if (y != 0)
res += calcp(n, x, y - 1, catx, currp / td, turn * -1);
if (x != n - 1)
res += calcp(n, x + 1, y, catx, currp / td, turn * -1);
if (y != n - 1)
res += calcp(n, x, y + 1, catx, currp / td, turn * -1);
}
else
{
res += calcp(n, x, y, catx + 1, currp, turn * -1);
}
return res;
}
int main()
{
int n = 3;
cout << fixed << setprecision(4) << calcp(n, n / 2, n / 2, 0, 1.0, MOUSE);
return 0;
}
这是原答案,题意理解错误,在网友提醒下改正。
#include <iostream>
#include <iomanip>
using namespace std;
float calcp(int n, int x, int y, int catx, float currp)
{
if (catx == n) return 0.0;
if (catx == x && y == n / 2) return currp;
int td = 4;
if (x == 0 || x == n - 1) td--;
if (y == 0 || y == n - 1) td--;
float res = 0.0;
if (x != 0)
res += calcp(n, x - 1, y, catx + 1, currp / td);
if (y != 0)
res += calcp(n, x, y - 1, catx + 1, currp / td);
if (x != n - 1)
res += calcp(n, x + 1, y, catx + 1, currp / td);
if (y != n - 1)
res += calcp(n, x, y + 1, catx + 1, currp / td);
return res;
}
int main()
{
int n = 3;
cout << fixed << setprecision(4) << calcp(n, n / 2, n / 2, -1, 1.0);
return 0;
}
补充图片