﻿ 算法 – 采访面试问题…分组数组 - 代码日志

#### 算法 – 采访面试问题…分组数组

Problem: Integer Partition without Rearrangement

Input: An arrangement S of non negative numbers {s1, . . .
, sn} and an integer k.

Output: Partition S into k or fewer ranges, to minimize the maximum
of the sums of all k or fewer ranges,
without reordering any of the
numbers.*

> d [i] [1] =从1到n的每个i的和(s1 … si)

>当序列中没有元素时，很明显，只有一个间隔可以是(一个空的)，它的元素的和是0.这就是为什么对于从1到k的所有j，d [0] [j] = 0 。
>只有一个间隔可以是，很明显，解是序列的所有元素的和。所以d [i] [1] = sum(s1 … si)。
>现在我们考虑序列中有i个元素，间隔数是j，我们可以假设最后一个间隔是(si-t 1 … si)，其中t是不大于i的正整数，所以在这种情况下解决方案是最大(d [i-t] [j-1]，sum(si-t 1 … si)，但是我们希望解决方案是最小的，我们应该选择t使其最小化，所以我们将得到minfor = 1到i(max(d [i-t] [j-1]，sum(si-t 1 … si))。

S =(5,4,1,12)，k = 2

d [0] [1] = 0，d [0] [2] = 0

d [1] [1] = 5，d [1] [2] = 5

d [2] [1] = 9，d [2] [2] = 5

d [3] [1] = 10，d [3] [2] = 5

d [4] [1] = 22，d [4] [2] = 12

``````#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;

int main ()
{
int n;
const int INF = 2 * 1000 * 1000 * 1000;
cin >> n;
vector<int> s(n + 1);
for(int i = 1; i <= n; ++i)
cin >> s[i];
vector<int> first_sum(n + 1, 0);
for(int i = 1; i <= n; ++i)
first_sum[i] = first_sum[i - 1] + s[i];
int k;
cin >> k;
vector<vector<int> > d(n + 1);
for(int i = 0; i <= n; ++i)
d[i].resize(k + 1);
//point 1
for(int j = 0; j <= k; ++j)
d[0][j] = 0;
//point 2
for(int i = 1; i <= n; ++i)
d[i][1] = d[i - 1][1] + s[i]; //sum of integers from s[1] to s[i]
//point 3
for(int i = 1; i <= n; ++i)
for(int j = 2; j <= k; ++j)
{
d[i][j] = INF;
for(int t = 1; t <= i; ++t)
d[i][j] = min(d[i][j], max(d[i - t][j - 1], first_sum[i] - first_sum[i - t]));
}

cout << d[n][k] << endl;
return 0;
}
``````
http://stackoverflow.com/questions/6454598/stuck-with-an-interview-question-partitioning-of-an-array