1. 程式人生 > >小貓爬山(dfs)

小貓爬山(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。

 

輸出

輸出一個整數,最少需要多少美元,也就是最少需要多少輛纜車。

 

樣例輸入

複製樣例資料

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;
}
/**/