zoukankan      html  css  js  c++  java
  • AcWing P165 小猫爬山 题解

    Analysis

    这道题是搜索,类似于小木棍,加一些剪枝。

    第一个剪枝是如果当前的答案已经大于了我们已知的最小答案,不用说直接return返回即可。

    第二个剪枝是我们可以将小猫的体重从大到小排序,这样我们的搜索树就会缩短许多。

     1 #include<iostream>
     2 #include<cstdio>
     3 #include<cstring>
     4 #include<algorithm>
     5 #define maxn 18+10
     6 using namespace std;
     7 typedef long long ll;
     8 inline int read() 
     9 {
    10     int x=0;
    11     bool f=1;
    12     char c=getchar();
    13     for(; !isdigit(c); c=getchar()) if(c=='-') f=0;
    14     for(; isdigit(c); c=getchar()) x=(x<<3)+(x<<1)+c-'0';
    15     if(f) return x;
    16     return 0-x;
    17 }
    18 inline void write(int x)
    19 {
    20     if(x<0){putchar('-');x=-x;}
    21     if(x>9)write(x/10);
    22     putchar(x%10+'0');
    23 }
    24 int n,w,ans=99999999,l;
    25 int c[maxn],e[maxn];
    26 bool book[maxn];
    27 inline bool cmp(int a,int b){return a>b;}
    28 inline void dfs(int af,int la,int step,int cnt)
    29 {
    30     bool flag=0;
    31     int i;
    32     if(step>=ans)return;
    33     if(cnt==n+1)
    34     {
    35         ans=step;
    36         return;
    37     }
    38     for(i=n;i>=af;i--)
    39         if(book[i]==0&&c[i]<=la)
    40         {
    41             flag=1;
    42             break;
    43         }
    44     if(flag==0) 
    45     {
    46         for(i=1;i<=n;i++)
    47             if(book[i]==0)
    48                 break;
    49         book[i]=1;
    50         dfs(i,w-c[i],step+1,cnt+1);
    51         book[i]=0;
    52         return;
    53     }
    54     for(i=af;i<=n;i++)
    55     {
    56         if(book[i]==0&&c[i]<=la)
    57         {    
    58             book[i]=1;
    59             dfs(i,la-c[i],step,cnt+1);
    60             book[i]=0;
    61             if(c[i]==la||la==w)return;
    62             i=e[i];
    63         }
    64     }
    65         
    66 }
    67 int main()
    68 {
    69     n=read();w=read();
    70     for(int i=1;i<=n;i++)c[i]=read();
    71     sort(c+1,c+n+1,cmp);
    72     e[n]=n;
    73     for(int i=n-1;i>0;i--)
    74     {
    75         if(c[i+1]==c[i])e[i]=e[i+1];
    76         else e[i]=i;
    77     }
    78     dfs(1,w,0,1);
    79     write(ans+1);
    80     return 0;
    81 }
    请各位大佬斧正(反正我不认识斧正是什么意思)
  • 相关阅读:
    离散型随机变量及其分布列
    建立概率模型
    几何概型习题
    古典概型习题
    含绝对值符号的问题
    临界状态在数学中的应用
    古典概型中的几何体计数
    条件概率
    创建可以滚动的表格
    NoSQL数据库种类
  • 原文地址:https://www.cnblogs.com/handsome-zyc/p/11269464.html
Copyright © 2011-2022 走看看