【LightOj 1027】 A Dangerous Maze(II) (概率、dp)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sunshiness_s/article/details/82619785

题意

LightOJ 1027
只不过添加一个条件:可以知道前 k 个是走的哪个房间
问出去的期望时间

题解

知道前 k 个的意思为走了 k 个负数以后,这 k 个可以不必走
定义 d p [ i ] 表示已经记录 i 个负数的期望时间
答案即为 d p [ 0 ]

下面的讨论中,我们定义 s u m 1 为正数和, s u m 2 为负数和; c n t 1 为正数个数, c n t 2 为负数个数

对于每一个 d p [ i ] 的结果,显然分为直接出去和再次回到原点的和,直接出去就是 s u m 1 n i 再次回到原点的和为 c n t 2 i n i ( s u m 2 c n t 2 + d p [ i + 1 ] ) s u m 2 c n t 2 表示剩下 c n t 2 i 个负数中随机选一个的期望,因为已选的 i 个数是随机的、再选的数也是随机的,所有也就相当于所有复数中选一个,即负数平均数; d p [ i + 1 ] 表示从原点随机选点出去的概率)
所有就有 d p [ i ] = s u m 1 n i + c n t 2 i n i ( s u m 2 c n t 2 + d p [ i + 1 ] )

下面我们来思考一波初值, f [ k + 1 ] 的时候已经不记得第一个了,因此 i = k 的式子中 f [ k + 1 ] = f [ k ] ,解一下,可知 d p [ k ] = s u m 1 + c n t 2 k c n t 2 s u m 2 n c n t 2

然而这样是不对的,因为有可能可以记录的 k 是比负数的个数还要大,那么 d p [ k ] 就没有用了,只有 d p [ 1 ~ c n t 2 ] 是有用的,因此把 k = c n t 2
c n t 2 = n 时,已经没有负数,所有出不去。和上一题一样,只不过上题输出 i n f ,此题输出 1

代码

#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std; 
#define N 100010
int n,T,k,sum1,sum2,cnt1,cnt2;
double f[N];
int main(){
    scanf("%d",&T);
    for(int tt=1;tt<=T;tt++){
        scanf("%d%d",&n,&k);
        sum1=sum2=cnt1=cnt2=0;
        for(int i=1;i<=n;i++){
            int x;scanf("%d",&x);
            if(x>0) sum1+=x,cnt1++;
            else sum2-=x,cnt2++; 
        }
        if(cnt2==n){printf("Case %d: -1\n",tt);continue;}
        if(k>=cnt2) k=cnt2,f[k]=(double)sum1/cnt1;
        else f[k]=(double)(sum1+(double)(cnt2-k)*sum2/cnt2)/(n-cnt2);
        for(int i=k-1;i>=0;i--){
            f[i]=(double)sum1/(n-i)+(double)(cnt2-i)*(f[i+1]+(double)sum2/cnt2)/(n-i);
        }
        printf("Case %d: %lf\n",tt,f[0]);
    }
    return 0;
} 

猜你喜欢

转载自blog.csdn.net/sunshiness_s/article/details/82619785