Codeforces Round #533(Div. 2) A.Salem and Sticks

本文介绍了一个CodeForces竞赛题目1105A的解决方案,目标是最小化给定数组中元素与某数t的绝对差之和。通过枚举和暴力计算的方法找到了满足条件的最优解,提供了完整的C++代码实现。

链接:https://codeforces.com/contest/1105/problem/A

题意:

给n个数,找到一个数t使i(1-n)∑|ai-t| 最小。

ai-t 差距1 以内都满足

思路:

暴力,枚举。

代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int MAXN = 1000+5;
int a[MAXN];


int main()
{
    int n;
    scanf("%d",&n);
    for (int i = 1;i<=n;i++)
        scanf("%d",&a[i]);
    int t,cost = 1e6;
    for (int i = 1;i<=100;i++)
    {
        int key = i;
        int sum = 0;
        for (int j = 1;j<=n;j++)
        {
            if (a[j] < key-1)
                sum += abs(a[j] - (key-1));
            if (a[j] > key+1)
                sum += abs(a[j] - (key+1));
        }
        if (sum < cost)
        {
            cost = sum;
            t = key;
        }
    }
    printf("%d %d\n",t,cost);

    return 0;
}

  

转载于:https://www.cnblogs.com/YDDDD/p/10297497.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值