题目1255:骰子点数概率(动态规划)

提交总是Wrong Answer,觉得自己的代码是没有问题的,如4个骰子的和为4的情况只能有一个,就是4个全部为1

题意:给出n个骰子,计算所有骰子朝上一面的点数之和为S对应的概率

思路:用dp(i,j)表示i个骰子和为j时的概率,有dp(i,j)=(dp(i-1,j-1)+dp(i-1,j-2)+..+dp(i-1,j-6)) * pow(1.0/6, i)

代码如下:

import java.io.FileInputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.StreamTokenizer;

class Main
{
    private  boolean DEBUG = true;

    private  BufferedReader cin;
    private  PrintWriter cout;
    private int n, t = 0;
    private StreamTokenizer tokenizer;
    private int[][] dp = new int[1000 + 1][1000 * 6 + 1];

    private void init()
    {
        try {
            if (DEBUG) {
                cin = new BufferedReader(new InputStreamReader(new FileInputStream("d:\\OJ\\jiudu.txt")));
            } else {
                cin = new BufferedReader(new InputStreamReader(System.in));
            }

            tokenizer = new StreamTokenizer(cin);
            cout = new PrintWriter(new OutputStreamWriter(System.out));
            preprocess();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    private int next()
    {
        try {
            tokenizer.nextToken();
            if (tokenizer.ttype == StreamTokenizer.TT_EOF) return -1;
            else if (tokenizer.ttype == StreamTokenizer.TT_NUMBER) return (int)tokenizer.nval;
            else return -1;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return -1;
        }
    }

    private void preprocess()
    {
        for (int i = 1; i <= 6; i++)
        {
            dp[1][i] = 1;
        }

        for (int i = 2; i <= 1000; i++) {
            for (int j = i; j <= i * 6; j++) {
                for (int k = 1; k <= 6 && k < j; k++) {
                    dp[i][j] += dp[i - 1][j - k];
                }
            }
        }
    }

    private void solve()
    {
        if (t++ != 0) cout.println();

        double tmp = Math.pow(1.0 / 6, n);

        for (int i = n; i <= n * 6; i++) {
            cout.printf("%d: %.3f", i, tmp * dp[n][i]);
            cout.println();
        }
        cout.flush();

    }

    public void run()
    {
        init();

        while ((n = next()) > 0) {
            solve();
        }

    }

    public static void main(String[] args)
    {
        Main solver = new Main();
        solver.run();
    }
}


    原文作者:动态规划
    原文地址: https://blog.csdn.net/xiexingshishu/article/details/52330842
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞