Acwing 165. 小猫爬山 java

在这里插入图片描述
🐷 输入案列

5 1996
1
2
1994
12
29

🐷 输出案列

2

👵 优先搜索可能方案比较少的分支
🤠 DFS+剪枝:排序,优先处理大的
🤠 枚举 猫?枚举 车?不重不漏,猫放缆车,能放则放,不能放则新开一辆
🤠 dfs 参数:传递方案
🤠 原题地址
🤠 java Arrays.sort(数组)不支持 int 类型自定义比较器。。。

import java.io.*;
import java.util.*;

public class Main
{
	static int N = 19, n, w, ans;
	static int[] a = new int[N];// 存猫的重量
	static int[] car = new int[N];// 存每辆缆车的已经装的重量

	public static void main(String[] args) throws IOException
	{
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		String[] split = in.readLine().split(" ");
		n = Integer.parseInt(split[0]);
		w = Integer.parseInt(split[1]);

		for (int i = 1; i <= n; i++)
		{
			// 失败,Integer便于排降序,但又不便于输入
//			a[i] = Integer.valueOf(Integer.parseInt(in.readLine()));
			a[i] = Integer.parseInt(in.readLine());
		}
		Arrays.sort(a, 1, n + 1);// 默认是升序 ( 如果要使用自定义比较器,int 不行,得是 Integer类型的数组)
		ans = n;// 答案最坏就是 每只猫一辆车
		dfs(n, 0);
		System.out.println(ans);
	}

	/**
	 * @param u 枚举猫
	 * @param k 当前租了多少车
	 */
	private static void dfs(int u, int k)
	{
		if (k >= ans)
		{
			return;
		}
		if (u == 0)// 所有猫都上车了
		{
			ans = k;
			return;
		}

		for (int i = 0; i < k; i++)
		{
			if (car[i] + a[u] <= w)
			{
				car[i] += a[u];
				dfs(u - 1, k);
				car[i] -= a[u];// 还原
			}
		}
		car[k] = a[u];
		dfs(u - 1, k + 1);
		car[k] -= a[u];

	}

}
posted @ 2023-03-02 22:02  兑生  阅读(14)  评论(0)    收藏  举报  来源
Live2D