You are in a maze; seeing n doors in front of you in beginning. You can choose any door you like. The probability for choosing a door is equal for all doors.
If you choose the ith door, it can either take you back to the same position where you begun in ximinutes, or can take you out of the maze after xi minutes. If you come back to the same position, you can remember last K doors you have chosen. And when you are about to choose a door, you never choose a door that is already visited by you. Or we can say that you never choose a door that is visited as one of the last K doors. And the probability of choosing any remaining door is equal.
Now you want to find the expected time to get out of the maze.
Input
Input starts with an integer T (≤ 100), denoting the number of test cases.
Each case contains a blank line and two integers n K (1 ≤ n ≤ 100, 0 ≤ K ≤ n). The next line contains n space separated integers. If the ith integer (xi) is positive, you can assume that the ithdoor will take you out of maze after xi minutes. If it's negative, then the ith door will take you back to the beginning position after abs(xi) minutes. You can safely assume that 1 ≤ abs(xi) ≤ 10000.
Output
For each case, print the case number and the expected time to get out of the maze. If it's impossible to get out of the maze, print '-1'. Otherwise print the result. Error less than 10-6 will be ignored.
Sample Input
4
2 0
10 10
2 0
10 -10
3 1
10 -10 -20
3 2
10 -10 -20
Sample Output
Case 1: 10
Case 2: 20.000
Case 3: 30.0000000000
Case 4: 25.0000000000
题解:定义sum1,sum2,cnt1,cnt2为正数之和,负数之和,正数的个数,负数的个数。
当已经记住i个位置时,对应答案dp[i]=sum1/(n-i)+(cnt2-i)/(n-i)*(sum2/cnt2+dp[i+1]); (其实就是分两种情况,1:该步能走出去,对应概率为1/(n-i),对应值为xi,由期望的线性性质得上式得第一部分:sum1/(n-i), 2:该步没有走出去:对应概率也为1/(n-i),有(cnt2-i)个选取方法,对应的值为(sum2/cnt2+dp[i+1]),由期望的线性性质即得上式得第二部分。
来看一下最终状态:令i=k,代入上式。并且dp[k]==dp[k+1],化简整理得:(注意要化简整理!)
dp[k]=(sum1+(cnt2-k)*sum2/cnt2)/(n-cnt2);
特别的,当k>=cnt2时,要另k=cnt2,并计算出对应的dp[k].
#include<bits/stdc++.h>
using namespace std;
double dp[110];
int main()
{
int t;
int n,k,tot=1;
cin>>t;
while(t--)
{
cout<<"Case "<<tot++<<": ";
cin>>n>>k;
double sum1,sum2,cnt1,cnt2;
sum1=sum2=cnt1=cnt2=0;
for(int i=1; i<=n; i++)
{
double x;
cin>>x;
if(x>0)
{
sum1+=x;
cnt1++;
}
else
{
sum2+=abs(x);
cnt2++;
}
}
if(cnt2==n)
{
cout<<"-1"<<endl;
continue;
}
else if(cnt2<=k)
{
k=cnt2;
dp[k]=sum1/(n-k);
}
else
dp[k]=(sum1+(cnt2-k)*sum2/cnt2)/(n-cnt2);
for(int i=k-1;i>=0;i--)
{
dp[i]=sum1/(n-i)+(cnt2-i)/(n-i)*(sum2/cnt2+dp[i+1]);
}
cout<<fixed<<setprecision(6)<<dp[0]<<endl;
}
return 0;
}