描述
What is possibility of rolling N dice and the sum of the numbers equals to M?
输入
Two integers N and M. (1 ≤ N ≤ 100, 1 ≤ M ≤ 600)
输出
Output the possibility in percentage with 2 decimal places.
很简单的动态规划,注:
1、dp[ i ][ j ]是i个色子投掷j点的概率
2、dp是概率,而不是可能的种类,不然6^n次方会超过long
直接上代码:
int n, m;
double dp[1000][1000] = {0};
int main(){
cin>>n>>m;
for(int i = 1; i<=m; i++){
if(i <= 6) dp[1][i] = 1.0/6;
else dp[1][i] = 0;
}
for(int i = 2; i<=n; i++){
for(int j = i; j <= m; j++){
for(int k = 1; k <= 6; k++){
if(j-k > 0) dp[i][j] += 1.0*dp[i-1][max(0, j-k)]/6;
}
}
}
printf("%.2f", 100*dp[n][m]);
return 0;
}
然后用递归也做了下:
int m, n;
double findNum(int ind, int tol){
if(ind == 0 || tol < 1) return 0;
double ans = 0;
if(tol > ind * 6 || tol < ind){
return 0;
}
if(tol == ind * 6 || tol == ind){
return 1;
}
if(ind == 1 && tol < 7) return 1.0 / 6;
else{
for(int i = 1; i<=6; i++){
ans += 1.0 * findNum(ind-1, tol-i) / 6;
}
}
return ans;
}
int main(){
cin>>n>>m;
double sum = findNum(n, m);
printf("%.2f", 100.0*sum);
return 0;
}
不出意外的runtime error