ZOJ 3582 Back to the Past(概率DP)

题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=4624

题意:A和B上各有n盏灯,初始时都是灭的。已知每天每个灯亮的概率为p。且亮了以后就不会再灭了。求A和B上各有不少于m盏灯亮的天数期望。

思路:f[i][j]表示分别还有i个和j个是灭的期望。

import java.util.*;

import java.text.*;

import java.math.*;



public class Main{

    

    static double EPS=1e-10;

    static double PI=Math.acos(-1.0);

    

    static double f[][]=new double[55][55];

    static double C[][]=new double[55][55];

    static double Log[]=new double[105];

    static double Log1[]=new double[105];

    static int n,m;

    static double p;

    

    

    public static void PR(String s){

        System.out.println(s);

    }

    

    public static void PR(int x)

    {

        System.out.println(x);

    }

    

    public static void PR(double s)

    {

        java.text.DecimalFormat d=new java.text.DecimalFormat("#.000000");

        System.out.println(d.format(s));

    }

    

    public static double DFS(int n1,int n2)

    {

        if(f[n1][n2]>=0) return f[n1][n2];

        if(n-n1>=m&&n-n2>=m) return 0;

        double ans=1,x;

        int i,j;

        for(i=0;i<=n1;i++) for(j=0;j<=n2;j++)

        {

            if(i==0&&j==0) continue;

            ans+=DFS(n1-i,n2-j)*C[n1][i]*Log[i]*Log1[n1-i]*C[n2][j]*Log[j]*Log1[n2-j];

        }

        ans/=(1-Log1[n1]*Log1[n2]);

        f[n1][n2]=ans;

        return ans;

    }

    

    public static void init()

    {

        int i,j;

        for(i=0;i<=50;i++)

        {

            C[i][0]=C[i][i]=1;

            for(j=1;j<i;j++) C[i][j]=C[i-1][j-1]+C[i-1][j];

        }

    }

    

    public static void main(String[] args){

  

        init();

        Scanner S=new Scanner(System.in);

        while(S.hasNext())

        {

            n=S.nextInt();

            m=S.nextInt();

            p=S.nextDouble();

            if(n==0&&m==0&&p==0) break;

            int i,j;

            for(i=0;i<=n;i++) for(j=0;j<=n;j++) 

            {

                f[i][j]=-1;

            }

            Log[0]=Log1[0]=1;

            for(i=1;i<=n;i++) Log[i]=Log[i-1]*p;

            for(i=1;i<=n;i++) Log1[i]=Log1[i-1]*(1-p);

            PR(DFS(n,n));

        }

    }

}

  

你可能感兴趣的:(ZOJ)