1. 程式人生 > >搜尋_DFS_CH2201_小貓爬山

搜尋_DFS_CH2201_小貓爬山

思路分析:

    依據每隻貓, 要麼放入當前某個纜車中, 要麼放在新的纜車中組織來解空間樹, 並進行合理的剪枝即可, 給出AC程式碼如下:

//CH2201_小貓爬山
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
const int MAXN = 20, NIL = 0x3f3f3f3f;
int cat[MAXN], N, W, res;
//path當前已安排的纜車集合first:纜車中貓重量, second:纜車中最小貓重量, level當前解空間樹層次 
void dfs(vector<int> &path, int level){
	if(path.size() > res) return;
	if(level > N){
		res = min(res, (int)path.size()); return;
	} 
	if(path.empty()){
		path.push_back(cat[level]), dfs(path, level + 1); return;
	}
	for(int i = 0; i < path.size(); ++i) 
		if(W - path[i] >= cat[level]) 
			path[i] += cat[level], dfs(path, level + 1), path[i] -= cat[level];
	path.push_back(cat[level]), dfs(path, level + 1), path.pop_back(); 	
}
int main(){
	scanf("%d %d", &N, &W);
	for(int i = 1; i <= N; ++i) scanf("%d", &cat[i]); 
	sort(cat + 1, cat + N + 1), reverse(cat + 1, cat + N + 1); 
	vector<int> path; res = NIL, dfs(path, 1), cout << res << endl;
	return 0;
}