openjudge-Moo Volume

本文探讨了一道编程问题,即计算一定数量的牛在草原上同时发出叫声时所产生的总音量。通过排序和公式推导,解决了如何计算每头牛与其它所有牛之间的距离总和,进而得出总音量。问题涉及到数学计算和算法应用,适合编程初学者了解排序和公式推导的基本概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

排序+简单公式推导

描述

Farmer John has received a noise complaint from his neighbor, Farmer Bob, stating that his cows are making too much noise.

FJ's N cows (1 <= N <= 10,000) all graze at various locations on a long one-dimensional pasture. The cows are very chatty animals. Every pair of cows simultaneously carries on a conversation (so every cow is simultaneously MOOing at all of the N-1 other cows). When cow i MOOs at cow j, the volume of this MOO must be equal to the distance between i and j, in order for j to be able to hear the MOO at all. Please help FJ compute the total volume of sound being generated by all N*(N-1) simultaneous MOOing sessions.
输入
* Line 1: N

* Lines 2..N+1: The location of each cow (in the range 0..1,000,000,000).
输出
There are five cows at locations 1, 5, 3, 2, and 4.
样例输入
5
1
5
3
2
4
样例输出
40
提示
INPUT DETAILS:

There are five cows at locations 1, 5, 3, 2, and 4.

OUTPUT DETAILS:

Cow at 1 contributes 1+2+3+4=10, cow at 5 contributes 4+3+2+1=10, cow at 3 contributes 2+1+1+2=6, cow at 2 contributes 1+1+2+3=7, and cow at 4 contributes 3+2+1+1=7. The total volume is (10+10+6+7+7) = 40.


题目是比较好理解的,关键是找出规律,并且推导出公式


简单题。
题目大意是说求n个牛相互之间距离和,如hint所描述的一样。
首先将这些牛的位置排序。
然后得出有n头牛时,相邻两头牛间距离相加的次数。(如下)
例如5头牛时:设这5头牛为abcde则:
a   b   c   d   e
  4   3   2   1      >>a叫的时候  (注意,这里:  a->e ==  a->b + b->c + c->d + d->e  )
  1   3   2   1      >>b叫的时候
  1   2   2   1      >>c叫的时候
  1   2   3   1      >>d叫的时候
  1   2   3   4      >>e叫的时候
求和得:
  8   12   12   8
通过尝试,得到如下规律:
n=2                2
n=3                4    4
n=4                6    8    6
n=5                8    12  12  8
n=6                10  16  18  16  10 
。。。。。。。。。。。。。。。。。

#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 100000000;
long long n,i,j,sum;//注意要用long long ,poj好像不能用__int64,这好像有点坑爹,害我wrong了一遍.....
long long a[maxn];
int main()
{
    while(~scanf("%lld",&n))
    {
        for(i=0;i<n;i++)
            scanf("%lld",&a[i]);
        sum=0;
        sort(a,a+n);
        for(j=1;j<n;j++)
        {
            sum=sum+(a[j]-a[j-1])*j*(n-j)*2;
        }
        printf("%lld\n",sum);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值