cf 295 div 2 B (bfs)

來源:互聯網
上載者:User

標籤:

題意:給出 n、m 兩數,可以對 n 進行兩種操作 減一或者乘二,操作過程中 n 必須保證非負,問使 n 變為 m 至少需要幾步操作。

這是我練水題的時候做到的,題目不難,只是我 bfs 一直沒怎麼用過比較不熟練,RE 了兩發,就整理了這題。

首先,若 n==m ,那麼步驟數就是 0 ,而若 n > m ,n 進行乘二的操作就會使 n 離 m 更遠,所以必然是一直減一,於是步驟數就是 n -m ;

若 n < m , 此時由於中間的步驟並不確定,就可以用 bfs 搜尋,但是由於使用數組記錄某個數字是否被訪問過,當數組並沒有刻意開很大的時候,就必須先判斷對 n 進行操作後的值是否在數組範圍內,而不能先判斷其數組值,我就因此 RE 了兩次,還是需要注意的。

 1 #include<stdio.h> 2 #include<string.h> 3 #include<queue> 4 using namespace std; 5  6 bool f[20005]; 7 int b[20005]; 8  9 int main(){10     int n,m;11     while(scanf("%d%d",&n,&m)!=EOF){12         if(n>=m)printf("%d\n",n-m);13         else{14             memset(f,0,sizeof(f));15             memset(b,0,sizeof(b));16             f[n]=1;17             b[n]=0;18             queue<int>q;19             while(!q.empty()){20                 q.pop();21             }22             q.push(n);23             int ans=0;24             while(!q.empty()){25                 int a=q.front();26                 q.pop();27                 if(a<m){28                     if(!f[2*a]){29                         q.push(a*2);30                         f[a*2]=1;31                         b[a*2]=b[a]+1;32                         if(a*2==m){33                             ans=b[a*2];34                             break;35                         }36                     }37                 }38                 if((a-1)>0){39                     if(!f[a-1]){40                         q.push(a-1);41                         f[a-1]=1;42                         b[a-1]=b[a]+1;43                         if(a-1==m){44                             ans=b[a-1];45                             break;46                         }47                     }48                 }49             }50             printf("%d\n",ans);51         }52     }53     return 0;54 }
View Code

 

cf 295 div 2 B (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.