HDOJ1548(DFS超記憶體,BFS過了)

來源:互聯網
上載者:User

標籤:

DFS代碼

#include<iostream>#include<cstdio>using namespace std;#define Min(a,b) (a<b)?a:bconst int MAX_N=205;const int INF=0x30303030;int floors[MAX_N];int N, A, B;int step[MAX_N];int dfs(int k){    if(k<1||k>N)    return INF;    if(step[k]!=-1)    {        return step[k];    }    if(k==B)    {        return 0;    }    return step[k]=Min(dfs(k-floors[k])+1,dfs(k+floors[k])+1);}int main(){      while(scanf("%d",&N)!=EOF&&N!=0)      {          scanf("%d %d",&A, &B);          for(int i=1; i<=N; i++)          {              scanf("%d",&floors[i]);          }          memset(step,-1,sizeof(step));              int ans=dfs(A);          if(ans>=INF)          {              printf("-1\n");          }          else          {              printf("%d\n",ans);          }      }          return 0;}

BFS:AC代碼

#include<iostream>#include<cstdio>#include<cstring>#include<queue>using namespace std;const int MAX_N=205;const int INF=0x30303030;int floors[MAX_N];int N, A, B;typedef pair<int, int> P;int vis[MAX_N];int bfs(){    memset(vis, 0, sizeof(vis));    queue<P> que;    que.push(P(0,A));    vis[A]=1;    while(!que.empty())    {        P pos=que.front();que.pop();        int k=pos.second;        int step=pos.first;        if(k==B)        {            return step;        }        for(int i=-1; i<=1; i++)        {            int next=(k + i*floors[k]);            if(next>=1&&next<=N&&!vis[next])            {                vis[next]=1;                que.push(P(step+1,next));            }        }            }        return INF;}int main(){      while(scanf("%d",&N)!=EOF&&N!=0)      {          scanf("%d %d",&A, &B);          for(int i=1; i<=N; i++)          {              scanf("%d",&floors[i]);          }          int ans=bfs();          if(ans==INF)          {              printf("-1\n");          }          else          {              printf("%d\n",ans);          }      }          return 0;}

 

HDOJ1548(DFS超記憶體,BFS過了)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.