小猫爬山(dfs)

小猫爬山

时间限制: 1 Sec  内存限制: 128 MB

题目描述

Freda和rainbow饲养了N只小猫,这天,小猫们要去爬山。经历了千辛万苦,小猫们终于爬上了山顶,但是疲倦的它们再也不想徒步走下山了(呜咕>_<)。
Freda和rainbow只好花钱让它们坐索道下山。索道上的缆车最大承重量为W,而N只小猫的重量分别是C1、C2……CN。当然,每辆缆车上的小猫的重量之和不能超过W。每租用一辆缆车,Freda和rainbow就要付1美元,所以他们想知道,最少需要付多少美元才能把这N只小猫都运送下山?

输入

第一行包含两个用空格隔开的整数,N和W。
接下来N行每行一个整数,其中第i+1行的整数表示第i只小猫的重量Ci。

输出

输出一个整数,最少需要多少美元,也就是最少需要多少辆缆车。

样例输入

复制样例数据

扫描二维码关注公众号,回复: 4526063 查看本文章
5 1996
1
2
1994
12
29

样例输出

2

提示

对于100%的数据,1<=N<=18,1<=Ci<=W<=10^8。

最近也不知道怎么了,不在状态,这种dfs都弄了很久,还是看别人的,下面附上我超时的代码,难受,我是枚举每个重量,其实只要枚举次数就行了。

/**/
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cctype>
#include <iostream>
#include <algorithm>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <stack>
#include <queue>

typedef long long LL;
using namespace std;

int n, w, a[20];
int vis[20], ans = 20;
int Sum = 0;

bool cmp(int x, int y){
	return x > y;
}

void dfs(int num, int sum, int cnt, int tot){
	if(ans <= cnt) return ;
	if(num == n){
		ans = min(ans, cnt);
		return ;
	}
	int f = 0;
	for (int i = 1; i <= n; i++){
		if(vis[i]) continue;
		vis[i] = 1;
		if(sum + a[i] > w){
			vis[i] = 0;
			continue;
		}
		f = 1;
		dfs(num + 1, sum + a[i], cnt, tot + a[i]);
		vis[i] = 0;
	}
	if(!f && cnt + ceil(1.0 * (Sum - tot) / w) < ans) dfs(num, 0, cnt + 1, tot);
}

int main()
{
	//freopen("in.txt", "r", stdin);
	//freopen("out.txt", "w", stdout);

	scanf("%d %d", &n, &w);
	for (int i = 1; i <= n; i++){
		scanf("%d", &a[i]);
		Sum += a[i];
	}
	sort(a + 1, a + n + 1, cmp);
	dfs(0, 0, 0, 0);
	printf("%d\n", ans + 1);

	return 0;
}
/**/

这是正确的代码

/**/
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cctype>
#include <iostream>
#include <algorithm>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <stack>
#include <queue>

typedef long long LL;
using namespace std;

int n, w;
int a[20], p[20], sum, f;

void dfs(int n, int num){
	if(f) return;
	if(num == n){
		f = 1;
		return ;
	}
	for (int i = 1; i <= n; i++){
		if(p[i] + a[i] <= w){
			p[i] += a[i];
			dfs(n, num + 1);
			p[i] -= a[i];
			if(f) return ;
		}
	}
}

int main()
{
	//freopen("in.txt", "r", stdin);
	//freopen("out.txt", "w", stdout);

	scanf("%d %d", &n, &w);
	for (int i = 1; i <= n; i++) scanf("%d", &a[i]), sum += a[i];
	sort(a + 1, a + 1 + n, greater<int>());
	for (int i = ceil(1.0 * sum / w); i <= n; i++){
		f = 0;
		dfs(i, 0);
		if(f){
			printf("%d\n", i);
			break;
		}
	}

	return 0;
}
/**/

猜你喜欢

转载自blog.csdn.net/oneplus123/article/details/84978986