给定一个带有m面的骰子。骰子的第一个面包含一个点,第二个面包含两个点,依此类推,第m个面包含m个点。每张面孔都有几率出现 。我们的任务是在掷出骰子后计算预期的最大点数时代。
例子:
Input: 2 2
Output: 1.750000000000
Here the dice contains {1, 2}.
So, the sample space of throwing the dice two times =
{(1, 2), (1, 1), (2, 1), (2, 2)}
For (1, 2)–> maximum=2
For (1, 1)–> maximum=1
For (2, 2)–> maximum=2
For (2, 1)–> maximum=2
The probability of each outcome is 0.25
that is expectation equals to
(2+1+2+2)*(0.25) = 7/4 = 1.750000000000
Input: 6 3
Output: 4.958333333333
方法:
在这个问题上的关键观察是没有。一个数字最多可以出现的次数取决于其先前的数字。
对于第i个数字,它将是 。
以m = 6,n = 2为例。
最大值等于6的总数等于 。
最大值等于5的总数等于 。
同样,我们可以找到4,3,2和1。
6 6 6 6 6 6
5 5 5 5 5 6
4 4 4 4 5 6
3 3 3 4 5 6
2 2 3 4 5 6
1 2 3 4 5 6
枚举最大数量,分布将是一个具有m个长度边的n维超级立方体。每层将是一个大的立方体减去一个较小的立方体。
因此,我们的答案将是从1到m的所有第i个元素的和:
计算中可能会导致溢出,因此我们可以将除数移到总和中并进行计算反而。
C++
// CPP program for above implementation
#include
using namespace std;
// Function find the maximum expectation
double expect(double m, double n)
{
double ans = 0.0, i;
for (i = m; i; i--)
// formula to find the maximum number and
// sum of maximum numbers
ans += (pow(i / m, n) - pow((i - 1) / m, n)) * i;
return ans;
}
// Driver code
int main()
{
double m = 6, n = 3;
cout << expect(m, n);
return 0;
}
Java
// Java program for above implementation
class GFG
{
// Function find the maximum expectation
static double expect(double m, double n)
{
double ans = 0.0, i;
for (i = m; i > 0; i--)
// formula to find the maximum number
// and sum of maximum numbers
ans += (Math.pow(i / m, n) -
Math.pow((i - 1) / m, n)) * i;
return ans;
}
// Driver code
public static void main(String[] args)
{
double m = 6, n = 3;
System.out.println(String.format("%.5f",
expect(m, n)));
}
}
// This code is contributed by mits
Python3
# Python3 program for finding maximum
# number of dots after throwing a
# dice N times.
# Function to find the maximum
# expectation
def expect(m,n) :
ans = 0.0
i = m
while (i):
# formula to find the maximum
# number and
# sum of maximum numbers
ans += (pow(i / m, n) - pow((i-1) / m, n)) * i
i -= 1
return ans
# Driver code
if __name__ == "__main__" :
# multiple assignments
m,n = 6,3
# function calling
print(expect(m,n))
C#
// C# program for above implementation
using System;
class GFG
{
// Function find the maximum expectation
static double expect(double m, double n)
{
double ans = 0.0, i;
for (i = m; i > 0; i--)
// formula to find the maximum number
// and sum of maximum numbers
ans += (Math.Pow(i / m, n) -
Math.Pow((i - 1) / m, n)) * i;
return ans;
}
// Driver code
public static void Main()
{
double m = 6, n = 3;
Console.WriteLine(expect(m, n));
}
}
// This code is contributed
// by Akanksha Rai
PHP
4.95833
时间复杂度: O(m)