P2911 [USACO08OCT] Bovine Bones G

题面翻译

贝茜喜欢玩棋盘游戏和角色扮演游戏,所以她说服了约翰开车带她去小商店.在那里她买了三个骰子。这三个不同的骰子的面数分别为 s 1 , s 2 , s 3 s_1,s_2,s_3 s1,s2,s3

对于一个有 S S S 个面的骰子每个面上的数字是 1 , 2 , 3 , … , S 1,2,3,\ldots,S 1,2,3,,S。每个面(上的数字)出现的概率均等。贝茜希望找出在所有“三个面上的数字的和”中,哪个和的值出现的概率最大。

现在给出每个骰子的面数,需要求出哪个所有“三个面上的数字的和”出现得最频繁。如果有很多个和出现的概率相同,那么只需要输出最小的那个。

数据范围: 2 ≤ s 1 ≤ 20 2\le s_1\leq 20 2s120 2 ≤ s 2 ≤ 20 2 \leq s_2\leq 20 2s220 2 ≤ s 3 ≤ 40 2 \leq s_3\leq 40 2s340

题目描述

Bessie loves board games and role-playing games so she persuaded Farmer John to drive her to the hobby shop where she purchased three dice for rolling. These fair dice have S1, S2, and S3 sides

respectively (2 <= S1 <= 20; 2 <= S2 <= 20; 2 <= S3 <= 40).

Bessie rolls and rolls and rolls trying to figure out which three-dice sum appears most often.

Given the number of sides on each of the three dice, determine which three-dice sum appears most frequently. If more than one sum can appear most frequently, report the smallest such sum.

POINTS: 70

输入格式

* Line 1: Three space-separated integers: S1, S2, and S3

输出格式

* Line 1: The smallest integer sum that appears most frequently when the dice are rolled in every possible combination.

1.题目分析

用到了桶排序的标记思想,即将数值作为数组的下标,数组的值加一,统计所有数值出现的次数。
这道题大概的题意是:给定三个数,每一个数对应一个数列:从1到该数,
三个数就会有三个数列,三个数列里的所有元素进行排列再求和,统计所有和的情况,找到和出现次数最多的情况,打印出此时和的值。值得注意的是,当次数恰好相同时,就取和较小的情况。

2.题目思路

计算三数相加的所有情况,将和的次数统计到数组,循环结束后,遍历数组,统计非零的数,计算最大值即最频繁的次数,循环结束,再一次遍历数组,通过最大值寻找最小索引,值得一提的是,找到第一个最大值时,直接跳出循环。

3.代码实现

#include 

int main() {
    int s1, s2, s3;
    scanf("%d%d%d", &s1, &s2, &s3);
    int sum = 0;
    int arr[100] = {0};
    int max = 0;
    //计算三数相加的所有情况
    for (int i = 1; i <= s1; ++i) {
        for (int j = 1; j <= s2; ++j) {
            for (int k = 1; k <= s3; ++k) {
                sum = i + j + k;
                //将和的次数统计到数组
                arr[sum] += 1;
                sum = 0;
            }
        }
    }

    for (int i = 0; i < 100; ++i) {
        //统计非零的数,计算最大值即最频繁的次数
        if (arr[i] !=0) {
            //判断最大值
            if (max < arr[i]) {
                max = arr[i];
            }
        }
    }
    //通过最大值寻找最小索引
    for (int i = 0; i < 100; ++i){
        //找到第一个最大值后,直接跳出循环
        if (arr[i] == max){
            printf("%d",i);
            break;
        }
    }

    return 0;
}

你可能感兴趣的:(刷题go,go,go,算法)