266. Expect Distance
Little K is trapped in a cave (cave A).
From cave A, there is two paths, in one path, it takes xx kilometers to go back cave A; the other one takes 22 kilometers to go to cave B.
From cave B, there is two paths, in one path, it takes yy kilometers to go to cave A; the other one takes zz kilometers to go to the exit C.
Little K always forget paths he walked, everytime he is in a cave, he will choose the path in equally probability.
Please calculate the expect distance to go out of the cave.
Example
Input:
x = 1
y = 2
z = 1
Output:
9
Notice
x, y, zx,y,z are all integeral, 1 <= x, y, z <= 10^81<=x,y,z<=10
8
解法1:
这是一道数学题。一开始没思路,请教了高手才明白。
设从A点走到出口的数学期望为EA, 从B点走到出口的数学期望为EB。可得
EA = (EA + x) / 2 + (EB + 2) / 2
EB = (EA + y) / 2 + Z / 2
通过上面2个方程可得
EA = 2 * x + y + z + 4
EB = x + y + z + 2
注意两个转移方程都是以A或B点的转出状态为准,不考虑转入状态,不然就搞糊涂了。
class Solution {
public:
/**
* @param x: the distance from cave A to cave A.
* @param y: the distance from cave B to cave B.
* @param z: the distance from cave B to exit C.
* @return: return the expect distance to go out of the cave.
*/
int expectDistance(int x, int y, int z) {
return 2 * x + y + z + 4;
}
};