欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Beer Marathon(思维)

程序员文章站 2024-03-18 21:54:52
...

Beer Marathon

In the booths version of the popular annual Beer Marathon, many beer booths (also called beerstalls or beer stands) are installed along the track. A prescribed number of visits to difffferentbeer booths is a part of the race for all contestants. The distances between any two consecutivebeer booths should be exactly the same and equal to the particular value specifified in the racerules.

The company responsible for beer booths installation did the sloppy work (despite being excessively paid), left the beer booths on more or less random positions along the track and departedfrom the town. Fortunately, thanks to advanced AI technology, the company was able to reportthe exact positions of the beer booths along the track, measured in meters, with respect tothe particular anchor point on the track. The marathon committee is going to send out thevolunteers to move the beer booths to new positions, consistent with the race rules.

They want to minimize the total number of meters by which all beer booths will be moved.The start line and the fifinishing line of the race will be chosen later, according to the resultingpositions of the beer booths.

Input Specifification

The fifirst line of input contains two integers N and K (1 ≤ N, K ≤ 106), where N is the numberof beer booths and K is the prescribed distance between the consecutive beer booths. Thesecond line of input contains N pairwise difffferent integers x1, . . . , xN ( -10^6 ≤ xi ≤ 10^6), theoriginal positions, in meters, of the beer booths relative to the anchor point. The positive valuesrefer to the positions past the anchor point and the negative values refer to the positions beforethe anchor point.

Output Specifification

Output a single integer — the minimal total number of meters by which the beer booths shouldbe moved to satisfy the race rules.

样例输入1

3 1
2 5 7

样例输出1

3

样例输入2

10 4
140 26 69 55 39 64 2 89 78 421

样例输出2

511

题意

n 个啤酒摊,在 x 轴上给出位置,现要求改变位置,每个相距 k,问最少的总移动距离。

思路

先排序,假设 0 处为 x 负轴上的第一个啤酒摊的最佳需要移动到的位置。再将每次左右移动的距离排序,当移动的距离中一半为正一半为负时为最佳情况(差值可为 1)。

实现代码
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <cstring>

#define ll long long
using namespace std;
const int maxn = 1e6 + 10;
ll a[maxn];

int main() {
    int n;
    ll k;
    ll sum = 0;
    scanf("%d%lld", &n, &k);
    for (int i = 1; i <= n; i++) {
        scanf("%lld", &a[i]);
    }
    sort(a + 1, a + n + 1);
    for (int i = 1; i <= n; i++) {
        a[i] = a[i] - (ll) i * k;
    }
    sort(a + 1, a + 1 + n);
    int mid = (n + 1) / 2;
    ll use = a[mid];
    for (int i = 1; i <= n; i++) {
        sum = sum + abs(a[i] - use);
    }
    printf("%lld\n", sum);
    return 0;
}
相关标签: 杂题