BZOJ 1679 [Usaco2005 Jan]Moo Volume 牛的呼声

解法1:

N^2的暴力程序,卡卡常数就过了。

#include <cstdio>
#include <algorithm>
#include <cmath>

int n;
int a[10005];
long long tot;

inline bool Read(int &ret){
    char c;
    int flag = 1;
    if(c=getchar(),c==EOF) return 0;
    while(c!='-' && (c<'0'||c>'9')) c=getchar();
    flag = (c=='-') ? -1 :1;
    ret = (c=='-') ? 0 : (c-'0');
    while(c=getchar(),c>='0'&&c<='9') ret=ret*10+(c-'0');
    ret*=flag;
    return 1;
}

int main(){
    Read(n);
    for(register int i=1;i<=n;++i){
        Read(a[i]);
        for(register int j=1;j<i;j++){
            tot+=abs(a[j]-a[i]);
        }
    }
    tot*=2;
    printf("%lld\n",tot);
    return 0;
}

 

解法2:

排序后,每段距离的对答案的贡献值是 左边的牛×右边的牛。

#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#define LL long long
using namespace std;
int n,a[10005];
int main()
{
    scanf("%d",&n);
    for (int i=1;i<=n;i++)
    scanf("%d",&a[i]);
    sort(a+1,a+1+n);
    LL ans=0;
    for (int i=2;i<=n;i++)
    {
        ans=ans+(long long )(a[i]-a[i-1])*((i-1)*(n+1-i));
    }
    cout<<ans*2<<endl;
    return 0;
}

 

转载于:https://www.cnblogs.com/OIerLYF/p/7521324.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值