I have 2 values \$N\$ and \$K\$ (\$1 \le K \lt N \le 1.000\$), where \$N\$ indicates a number of values (\$0 \le \text{value}2 \le ... \le \text{value}N \le 1,000,000\$) to be read from input. The first value isn't on the input and will always be 0.
All \$N\$ values need to be organized on at most \$K\$ groups where the sum of the groups size is minimized.
The size of a group is defined by the distance between the two most distant values in the group (MAX_VALUE - MIN_VALUE
). If the group consists of only one value, its size is zero.
What is the minimum total value for the sum of the groups size if the values are organized optimally?
Here is an input sample:
5 2 1 2 5 6
Output sample:
3
My solution is a brute force search. This is a known problem. How can I do better than this solution?
#include <cstdio>
#include <queue>
#include <vector>
#include <limits>
#include <algorithm>
using groups = std::vector< std::vector<int> >;
int getTotalGroupsSize(groups &g){
unsigned long k = g.size();
int total = 0;
for (unsigned long i = 0; i < k; ++i) {
int max = std::numeric_limits<int>::min();
int min = std::numeric_limits<int>::max();
std::vector<int> &subGroup = g[i];
for (int j = 0; j < subGroup.size(); ++j) {
max = std::max(max, subGroup[j]);
min = std::min(min, subGroup[j]);
}
total += (max - min);
}
return total;
}
int getOptimallSum(std::queue<int> &q, groups &g){
if(q.empty())
return getTotalGroupsSize(g);
int front = q.front();
q.pop();
int minDiff = std::numeric_limits<int>::max();
for (int i = 0; i < g.size(); ++i) {
g[i].push_back(front);
minDiff = std::min(minDiff,getOptimallSum(q, g));
g[i].pop_back();
}
q.push(front);
return minDiff;
}
int main(void){
int n,k;
while (scanf("%d",&n) != EOF) {
scanf("%d",&k);
std::queue<int> q;
q.push(0);
for (int i = 1; i < n; ++i) {
int value;
scanf("%d",&value);
q.push(value);
}
if(k >= n){
puts("0");
continue;
}
groups g(k);
printf("%d\n",getOptimallSum(q,g));
}
return 0;
}
N=5
, but you only input 4 numbers? \$\endgroup\$