昨天打了场cf,只做出第一道水题,而和我同级的队员都做出三道题,有点难过,落下太多,剩下的唯有好好补题。

Sagheer, the Hausmeister

昨天比赛时候写的BFS,到最后不好对上面有没有进行判断。

今天早上花一个半小时软磨硬泡出来的DFS

  1 #include <bits/stdc++.h>
  2 using namespace std;
  3 int n,m;
  4 char temp[16][105];
  5 int maze[16][105];
  6 int l[16];
  7 int r[16];
  8 const int inf = 0x3f3f3f3f;
  9 int dfs(int curfloor,int stairs)
 10 {
 11     if(curfloor>=n-1)
 12     {
 13         if(l[n-1]==inf)
 14         {
 15             return 0;
 16         }
 17         else
 18         {
 19             if(!stairs)
 20             {
 21                 return r[n-1] + 1; //末尾加1上1台阶
 22             }
 23             else
 24             {
 25                 return m - 1 - l[n-1] + 1;
 26             }
 27         }
 28     }
 29     if(l[curfloor]==inf)    //本楼道没有灯亮,就不用走了
 30     {
 31         int cost = dfs(curfloor+1,stairs);
 32         if(cost)
 33         {
 34             return cost+1;
 35         }
 36         else
 37         {
 38             return cost;
 39         }
 40     }
 41     else                       //有灯则继续考虑
 42     {
 43         int same = dfs(curfloor+1,stairs);              //先往上走走试试
 44         int different = dfs(curfloor+1,!stairs);
 45         int cost = 0;
 46         if(!stairs)  //0表示我是从下一层从左上来的
 47         {
 48             cost = same+r[curfloor]*(same>0?2:1)+1; //如果以后没有,我就停在最后的位置,不用绕回来了
 49             cost = min(cost,different+r[curfloor]+(m-1-r[curfloor])*(different>0?1:0)+1); //+1表示上到现在的台阶
 50         }
 51         else    //从右上
 52         {
 53             cost = same+(m-1-l[curfloor])*(same>0?2:1)+1;
 54             cost = min(cost,different+m-1-l[curfloor]+l[curfloor]*(different>0?1:0)+1);
 55         }
 56         return cost;
 57     }
 58 }
 59 int main()
 60 {
 61     cin>>n>>m;
 62     m += 2;
 63     for(int i=0;i<n;i++)
 64     {
 65         cin>>temp[i];
 66     }
 67     int v = n-1;
 68     memset(l,inf,sizeof(l));
 69     memset(r,0,sizeof(r));
 70     for(int i=0;i<n;i++)
 71     {
 72         for(int j=0;j<m;j++)
 73         {
 74             maze[i][j] = temp[v][j]-'0';
 75             if(maze[i][j]==1)
 76             {
 77                 l[i] = min(l[i],j);
 78                 r[i] = max(r[i],j);
 79             }
 80         }
 81         v--;
 82     }
 83     int cost = dfs(0,0);
 84     if(cost>0)
 85     {
 86         cout<<cost-1<<endl;
 87     }
 88     else
 89     {
 90         cout<<0<<endl;
 91     }
 92     return 0;
 93 }
 94 /*
 95 4 3
 96 00000
 97 00100
 98 00000
 99 00000
100 */
DFS

相关文章:

  • 2022-02-06
  • 2022-12-23
  • 2021-08-18
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-05
  • 2021-08-12
猜你喜欢
  • 2021-06-14
  • 2021-08-14
  • 2021-08-25
  • 2021-05-25
相关资源
相似解决方案