luogu P1361 小猫爬山 [iddfs]

题目描述

WD和LHX饲养了N只小猫,这天,小猫们要去爬山。经历了千辛万苦,小猫们终于爬上了山顶,但是疲倦的它们再也不想徒步走下山了。

WD和LHX只好花钱让它们坐索道下山。索道上的缆车最大承重量为W,而N只小猫的重量分别是C1、C2……CN。当然,每辆缆车上的小猫的重量之和不能超过W。每租用一辆缆车,WD和LHX就要付1美元,所以他们想知道,最少需要付多少美元才能把这N只小猫都运送下山?

输入输出格式

输入格式:

第一行包含两个用空格隔开的整数,N和W。

接下来N行每行一个整数,其中第i+1行的整数表示第i只小猫的重量C i。

输出格式:

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

输入输出样例

输入样例#1:
5 1996
1
2
1994
12
29
输出样例#1:
2

说明

数据范围与约定

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


My Solution

都已经是蒟蒻了solution写长一点吧

迭代加深排序iddfs的膜版之一,k从sum(data[0],data[1],...,data[n-1])/q到n之间

k表示最小可行答案(就是最后的答案啦)

注意data[0...n-1]从小到大排序

结果还是很短啊

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<iostream>
 4 #include<algorithm>
 5 using namespace std;
 6 
 7 inline int read(){
 8     char ch;
 9     int re=0;
10     while((ch=getchar())<'0'||ch>'9');
11     re=ch-'0';
12     while((ch=getchar())>='0'&&ch<='9')  re=re*10+ch-'0';
13     return re;
14 }
15 
16 const int maxn=19;
17 int data[maxn];
18 int q,n;
19 int k=0;
20 bool ok=0;
21 int car[maxn]={0};
22 
23 void init(){
24     n=read(),q=read();
25     for(int i=0;i<n;i++){
26         data[i]=read();
27         k+=data[i];
28     }
29     k/=q;
30 }
31 
32 void iddfs(int pos){
33     if(pos==n){
34         ok=1;
35         return;
36     }
37     for(int i=1;i<=k;i++)
38         if(car[i]+data[pos]<=q){
39             car[i]+=data[pos];
40             iddfs(pos+1);
41             car[i]-=data[pos];
42             if(ok)  return;
43         }
44 }
45 
46 inline bool compp(const int &n1,const int &n2){
47     return n1>n2;
48 }
49 
50 void solve(){
51     sort(data,data+n,compp);
52     while(k<=n){
53         iddfs(0);
54         if(ok){
55             printf("%d
",k);
56             return;
57         }
58         k++;
59     }
60 }
61 
62 int main(){
63     //freopen("temp.in","r",stdin);
64     init();
65     solve();
66     return 0;
67 }

别害怕别害怕  只是悲欢离合的梦啊
原文地址:https://www.cnblogs.com/ZYBGMZL/p/6857434.html