Algorithm Training Seal (dp)

Resource limit
Memory limit: 256.0MB C/C++ time limit: 1.0s Java time limit: 3.0s Python time limit: 5.0s
Problem description
  There are n types of stamps with the same probability of appearance. Little A bought m stamps, and asked for the probability that little A collected n kinds of stamps.
Input format
  One line of two positive integers n and m
Output format
  A real number P represents the answer, retaining 4 decimal places.
Sample input
2 3
sample output
0.7500
Data scale and convention
  1≤n, m≤20

import java.util.Scanner;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner s=new Scanner(System.in);
        int n=s.nextInt();
        int m=s.nextInt();
        double p=1.0/n;

        double[][] b=new double[m+1][n+1];
        if (n==1){
    
      //当n=1时m>n几率为1
            b[m][n]=1;
            System.out.printf("%.4f",b[m][n]);
            return;
        }
        if (n>1&&m<n){
    
     //当m<n时几率为0
            b[m][n]=0;
            System.out.printf("%.4f",b[m][n]);
            return;
        }
        for (int i = 1; i <=m; i++) {
    
    
            for (int j = 1; j <=n; j++) {
    
    
                if (i<j) b[i][j]=0;       //当m<n时几率为0
                if (j==1){
    
    
                    b[i][j]=Math.pow(p,i-1);        //当i张集齐1种的概率
                }else {
    
    
                    b[i][j]=b[i-1][j]*(j*1.0/n)+b[i-1][j-1]*((n-j+1)*1.0/n);        //当i张集齐j种的概率
                }

            }

        }

        System.out.printf("%.4f",b[m][n]);

    }
}

Guess you like

Origin blog.csdn.net/qq_54537215/article/details/123937707