[topcoder]TheConsecutiveIntegersDivOne

时间:2023-03-10 06:20:25
[topcoder]TheConsecutiveIntegersDivOne

http://community.topcoder.com/stat?c=problem_statement&pm=13625&rd=16278

首先,如果记得曼哈顿距离最小值那个问题,会想起一维的情况可证,点出现在中位数那里是最小的。这里也可证明,四个点,出现在中位数位置是最小的。

题解里的做法是,试探所有让某个想减的绝对值最小的情况。

我的代码有点丑,但过了:

#include <vector>
#include <algorithm> using namespace std; class TheConsecutiveIntegersDivOne {
public:
int find(vector <int> numbers, int k) {
sort(numbers.begin(), numbers.end());
int d = k / 2;
int left = 0;
int sumL = 0;
for (int i = left; i < left + d; i++) {
sumL += numbers[i];
}
int sumR = 0;
int right = left + d;
if (k % 2 == 1) {
right++;
}
for (int i = right; i < right + d; i++) {
sumR += numbers[i];
}
int result = sumR - sumL - d * d;
while (right + d < numbers.size()) {
sumL += numbers[left + d];
sumL -= numbers[left];
sumR += numbers[right + d];
sumR -= numbers[right];
result = min(result, sumR - sumL - d * d);
left++;
right++;
}
return result;
}
};