1. 程式人生 > >A Dangerous Maze (II)

A Dangerous Maze (II)

題解:期望dp,設正確的門有a個,平均耗時為sum1,錯誤的門有b個,平均耗時為sum2。 狀態轉移分2部分:

①當i==k時,即已經記住k次走錯的門,dp[k]=\frac{a*sum_1+(b-k)*(dp[k]+sum_2)}{n-k} ②當i<k時,dp[i]=\frac{a*sum1+(b-i)*(dp[i+1]+sum_2)}{n-i}

#include<bits/stdc++.h>
using namespace std;
const int MX = 105;
double dp[MX];
int x[MX];
int main(){
    int T,n,k;
  //  freopen("in.txt","r",stdin);
    scanf("%d",&T);
    for(int cas=1;cas<=T;cas++){
        memset(dp,0,sizeof(dp));
        scanf("%d%d",&n,&k);
        int a=0,b;
        double sum1=0,sum2=0;
        for(int i=0;i<n;i++) {
            scanf("%d",&x[i]);
            if(x[i]>0) {sum1+=x[i];a++;}
            else sum2+=abs(x[i]);
        }
        if(a==0) {
            printf("Case %d: -1\n",cas);
            continue;
        }
        b=n-a;
        if(a) sum1/=a;
        if(b) sum2/=b;
        k=min(k,b);
        dp[k]=sum1+(b-k)*sum2/a;
        for(int i=k-1;i>=0;i--){
            dp[i]=(dp[i+1]+sum2)*(b-i);
            dp[i]+=sum1*a;
            dp[i]/=n-i;
        }
        printf("Case %d: %.7f\n",cas,dp[0]);
    }
    return 0;
}