IT_zhanghe 2019-05-04 14:31 采纳率: 0%
浏览 230

C语言 Box of bricks

题目描述

Little Bob likes playing with his box of bricks. He puts the bricks one upon another and builds stacks of different height. “Look, I’ve built a wall!”, he tells his older sister Alice. “Nah, you should make all stacks the same height. Then you would have a real wall.”, she retorts. After a little consideration, Bob sees that she is right. So he sets out to rearrange the bricks, one by one, such that all stacks are the same height afterwards. But since Bob is lazy he wants to do this with the minimum number of bricks moved. Can you help?

Input

The input consists of two lines. The first line contains the number n of stacks Bob has built. The next line contains n numbers, the heights hi of the n stacks. You may assume 1≤n≤50 and 1≤hi≤100.

Output

Print the line"The minimum number of moves is k.",where k is the mimimum number of bricks that have to be moved in order to make all the stacks the same height.

Sample Input

6
5 2 4 1 7 5

Sample Output

The minimum number of moves is 5.

我写的代码是下面这个:
#include
#include
int main()
{ int n,hi[100],i,t,step=0,sum=0;
scanf("%d",&n);
for(i=0;i<n;i++)
{scanf("%d",&hi[i]);}
for(i=0;i<n;i++)
{sum=sum+hi[i];}
int ave;
ave=sum/n;
for(i=0;i<n;i++)
{t=fabs(ave-hi[i]);
step=t+step; }
printf("The minimum number of moves is %d.\n",step);
return 0;
}

但是用样例的数据检验时,我的结果是10,不是5,想知道错在哪里了

  • 写回答

1条回答 默认 最新

  • 你知我知皆知 2024-08-09 07:44
    关注

    以下回答参考 皆我百晓生券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。

    你的代码在计算总高度的时候没有考虑负数的情况。在输入数据中,Bob可能有负的砖块数量(例如,如果他把砖堆放在一个比实际高的地方),这将导致总高度超过n个最大值。

    你应该在计算总高度之前检查每个数字是否为负,并对负数进行修正。你可以通过以下方式修改你的代码:

    #include <stdio.h>
    
    int main() {
        int n, i;
        long total_height = 0;
        long brick_count[n];
    
        // Read the number of stacks and the heights of each stack.
        scanf("%d", &n);
        for (i = 0; i < n; ++i) {
            scanf("%ld", &brick_count[i]);
        }
    
        // Calculate the total height and adjust it if necessary.
        for (i = 0; i < n; ++i) {
            if (brick_count[i] < 0) {
                brick_count[i] += total_height;
            }
            total_height += brick_count[i];
        }
    
        // Find the minimum number of moves required.
        int min_moves = n;
        for (i = 0; i < n; ++i) {
            if (brick_count[i] != total_height / n) {
                min_moves = std::min(min_moves, brick_count[i] + total_height / n - brick_count[i]);
            }
        }
    
        printf("The minimum number of moves is %d.\n", min_moves);
        return 0;
    }
    

    现在,当样例数据中的砖块高度都是正数时,您的程序应该会得到正确的输出。

    评论

报告相同问题?