You are given a 3D grid, which has dimensions X, Y and Z. Each of the X x Y x Z cells contains a light. Initially all lights are off. You will have K turns. In each of the K turns,
- You select a cell A randomly from the grid,
- You select a cell B randomly from the grid and
- Toggle the states of all the bulbs bounded by cell A and cell B, i.e. make all the ON lights OFF and make all the OFF lights ON which are bounded by A and B. To be clear, consider cell A is (x1, y1, z1) and cell B is (x2, y2, z2). Then you have to toggle all the bulbs in grid cell (x, y, z) where min(x1, x2) ≤ x ≤ max(x1, x2), min(y1, y2) ≤ y ≤ max(y1, y2) and min(z1, z2) ≤ z ≤ max(z1, z2).
Your task is to find the expected number of lights to be ON after K turns.
Input
Input starts with an integer T (≤ 50), denoting the number of test cases.
Each case starts with a line containing four integers X, Y, Z (1 ≤ X, Y, Z ≤ 100) and K (0 ≤ K ≤ 10000).
Output
For each case, print the case number and the expected number of lights that are ON after K turns. Errors less than 10-6 will be ignored.
Sample Input
5
1 2 3 5
1 1 1 1
1 2 3 0
2 3 4 1
2 3 4 2
Sample Output
Case 1: 2.9998713992
Case 2: 1
Case 3: 0
Case 4: 6.375
Case 5: 9.09765625
大致题意:在一个三维坐标空间中,每一个点上都有一盏灯,一共X*Y*Z盏。操作K次,每一次随机的选择两盏灯(可以相同),然后将这两盏灯按题中所说形成的空间内的所有的灯的状态反转一遍,最初状态都是关着的,问经过K次操作后,所亮着的灯的期望数量是多少。
思路:经过K次操作后,如果某一点上的灯被按了奇数次,那么此时它是亮的,反之则不是,所以我们可以对每个位置上的灯单独进行计算,算出它经过K次操作后被按了奇数次的期望概率,然后将所有位置上的灯的期望概率加起来即可。对于某个位置(i,j,k)上的灯来说,如果它需要被按到,那么所选的那两个灯在每一维度上的坐标都不能在该灯的同一侧,拿X轴来说,它被按到的概率即为(1-(i-1)x(i-1)-(X-i)x(X-i)) /X^2,其余两维相似。所以该灯被按到的概率P=X上的概率 * Y上的概率 *Z上的概率。假设f(n)表示该位置上的灯在经过K次操作后被按了奇数次的概率期望,那么1-f(K)即表示被按了偶数次的概率,状态转移方程即f(K)=f( K-1 )x( 1-p )+( 1-f( K-1 ) )xP 化简得f(K)=f(K-1)x(1-2P)+P,但是如果就直接这样递推去算的话这部分的时间复杂度是O(K)超时,所以我们还需继续对这个公式进行推导,最后能得到它的一个通项公式:
f(K)=(1-(1-2 x P)^K)/2
推导过程如下
代码如下
#include<bits/stdc++.h>
using namespace std;
double kpow(double x,int n) // x^n
{
double res=1;
while(n>0)
{
if(n & 1)
res=res*x;
x*=x;
n >>= 1;
}
return res;
}
double get(int w,int i)
{
return 1.0*(w*w-(i-1)*(i-1)-(w-i)*(w-i))/w/w;
}
int main()
{
int T;
scanf("%d",&T);
for(int cas=1;cas<=T;cas++)
{
int X,Y,Z,K;
double ans=0;
scanf("%d%d%d%d",&X,&Y,&Z,&K);
for(int i=1;i<=X;i++)
for(int j=1;j<=Y;j++)
for(int k=1;k<=Z;k++)
{
double P=get(X,i)*get(Y,j)*get(Z,k);
ans+=(1-kpow(1-2*P,K))/2;
}
printf("Case %d: %.10lf\n",cas,ans);
}
return 0;
}