粘木棍
典型的桶装小球模型:有n个桶放入m个小球,求一些东西, 比如:
- 桶的容量都一样,求每一个桶的最小值1723. 完成所有工作的最短时间
- 求桶的之间放入小球的最大差值。(本题)
暴力
因为数据量比较小,所以这里可以使用暴力做法,做法如下:
package lanqiao.imporve;
import org.omg.CORBA.INTERNAL;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
/**
* @author: Zekun Fu
* @date: 2022/10/12 18:09
* @Description: 蓝桥杯粘木棍
* m, n都很小,所以可以直接暴力
*
* 典型的组合问题,使用枚举子集的方式进行
*
* 就是说,m个桶,放n个球,求最小桶和的差值
*
*
*/
public class ZhanMuGun {
private static int n, m;
private static int[] a;
public static int dfs(int[] bucket, int cur) {
if (cur == n) {
int maxv = Integer.MIN_VALUE, minv = Integer.MAX_VALUE;
for (int i = 0; i < m; i++) {
if (bucket[i] == 0) return Integer.MAX_VALUE;
minv = Math.min(minv, bucket[i]);
maxv = Math.max(maxv, bucket[i]);
}
return maxv - minv;
}
int ans = Integer.MAX_VALUE;
for (int i = 0; i < m; i++) {
// 把当前的球放进i号桶中
bucket[i] += a[cur];
ans = Math.min(ans, dfs(bucket, cur + 1));
bucket[i] -= a[cur];
}
return ans;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
int[] bucket = new int[m];
System.out.println(dfs(bucket, 0));
}
}