1904. Put small balls
Given the number of balls in n buckets, buckets can be operated k times (one ball can be taken out of the bucket, or one ball can be added), and each bucket has a specified maximum capacity W[i]. Find the minimum square value of the maximum difference between two adjacent buckets after operation.
Example
Example 1:
Input:
5
6
[1,2,3,4,5]
[15,15,15,15,15]
Output:
0
Clarification
There are a total of 5 buckets, with a maximum of 6 operations. The balls in the buckets are 1,2,3,4,5, and the maximum capacity of the buckets is 15,15,15,15,15,15.
Notice
n\leq100n≤100
W[i]\leq100W[i]≤100
Input test data (one parameter per line)How to understand a testcase?
解法1: Binary Search + DP
这题跟Wood Cut和Copy book那题很像,都是基于Binary Search。不同的是那2题采用贪婪法,而本题采用DP。
//思路参考九章:
dp[i][j]表示A[i]=j时,A[i]与A[i-1]差值不大于target所需要的最小变动球数。
当A[i]=j时,A[i-1]的范围为[max(0, j - target),min(W[i - 1], j + target)]。
DP思路如下:
dp[0][j] = abs(j - A[0])
//i > 0
dp[i][j] = min(dp[i][j], dp[i - 1][k] + abs(j - A[i])) //k在[max(1, j - target),min(100, j + target)]中取值。
注意:
1) dp初始值不能用INT_MAX,因为后面的
dp[i - 1][k] + abs(j - A[i])
会溢出。
class Solution {
public:
/**
* @param n: the number of buckets
* @param k: the maximum times of operations
* @param A: the number of balls in each bucket
* @param W: the maximum capacity of each bucket
* @return: return the minimum square value of the maximum difference
*/
int getAns(int n, int k, vector<int> &A, vector<int> &W) {
int result = INT_MAX;
int start = 0, end = 100;
while(start + 1 < end) {
int mid = start + (end - start) / 2;
if (calMinCost(n, A, W, mid) <= k) {
result = min(result, mid);
end = mid;
} else {
start = mid;
}
}
if (calMinCost(n, A, W, start) <= k) {
result = min(result, start);
} else if (calMinCost(n, A, W, end) <= k) {
result = min(result, end);
}
return result * result;
}
private:
int calMinCost(int n, vector<int> &A, vector<int> &W, int target) {
vector<vector<int>> dp(n, vector<int>(101, 0x3f3f3f3f));
for (int j = 0; j <= W[0]; ++j) {
dp[0][j] = abs(j - A[0]);
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j <= W[i]; ++j) {
if (i == 0) continue;
for (int k = max(0, j - target); k <= min(W[i - 1], j + target); ++k) {
dp[i][j] = min(dp[i][j], dp[i - 1][k] + abs(j - A[i]));
}
}
}
int result = INT_MAX;
for (int i = 0; i <= 100; ++i) {
result = min(result, dp[n - 1][i]);
}
return result;
}
};