HDU3220逆向思維的BFS

來源:互聯網
上載者:User

這道題有兩個重要的地方,一個是對題目的理解,合法的操作只有一種,那就是對相鄰的兩個狀態不同的燈泡進行交換狀態的操作,也就是說,相鄰的燈泡如果都是亮著的或者暗著的,那麼不能對這條邊進行操作。

第二點,那就是由於所有的狀態的目標狀態都是一樣的,那麼我們就可以從目標狀態進行BFS,計算出其他狀態到目標狀態要多少步,注意當BFS的步數大於3的時候,就不要將其子狀態放入隊列中,為了方便,之前將全部的狀態的需要步數設定為5,這樣即使沒有訪問的狀態,步數也是大於3的,這個演算法的時間複雜度是O(32^3),完全可以接受,之後就是O(1)的查詢。

為了方便BFS,最佳化空間,運用位壓縮,將16個燈泡的狀態用一個int來存放,高位存放低編號的燈泡,裝換的時候就用異或運算即可。

數組x和y用來對應32對相鄰的燈泡

 

My Code:

 

#include <iostream><br />#include <cstdio><br />#include <cstring><br />#include <cstdlib><br />#include <queue></p><p>using namespace std;</p><p>const int MAX=1<<17;<br />const int x[32]={0,1,3,11,10,8,10,2,8,9,9,0,0,1,3,11,10,8,9,2,12,13,13,4,14,6,12,4,5,7,15,14};<br />const int y[32]={1,3,11,10,8,0,2,3,9,1,11,2,4,5,7,15,14,12,13,6,13,5,15,6,6,7,4,5,7,15,14,12};<br />const int aim=((1<<8)-1);<br />int dist[MAX];</p><p>struct Node<br />{<br /> int st;<br /> int depth;<br />};</p><p>int hash(const int& st,const int& op)<br />{<br /> return st^((1<<(15-x[op]))|(1<<(15-y[op])));<br />}</p><p>void bfs()<br />{<br /> Node node,next;<br /> queue<Node> q;</p><p> node.st=aim;<br /> node.depth=0;<br /> dist[aim]=0;<br /> q.push(node);<br /> while(!q.empty())<br /> {<br /> node=q.front();<br /> q.pop();<br /> if(node.depth>3)<br /> break;<br /> next.depth=node.depth+1;<br /> for(int i=0;i<32;i++)<br /> {<br /> if((node.st&(1<<(15-x[i])))!=(node.st&(1<<(15-y[i]))))<br /> {<br /> next.st=hash(node.st,i);<br /> if(dist[next.st]==1000)<br /> {<br /> dist[next.st]=next.depth;<br /> q.push(next);<br /> }<br /> }<br /> }<br /> }<br />}</p><p>int main()<br />{<br /> int t,cnt=0;<br /> int a;<br /> int st;</p><p> for(int i=0;i<MAX;i++)<br /> {<br /> dist[i]=1000;<br /> }<br /> bfs();</p><p> scanf("%d",&t);<br /> while(t--)<br /> {<br /> cnt++;<br /> st=0;<br /> for(int i=0;i<16;i++)<br /> {<br /> scanf("%d",&a);<br /> if(a==1)<br /> st|=(1<<(15-i));<br /> }</p><p> a=dist[st];<br /> if(a>3)<br /> {<br /> printf("Case #%d: more/n",cnt);<br /> }<br /> else<br /> {<br /> printf("Case #%d: %d/n",cnt,a);<br /> }<br /> }</p><p> return 0;<br />}<br />

 

總結:在搜尋的時候,我們經常要想到是否有可以最佳化的方法,位壓縮是一個很好的節約空間的方式,另外,這題不可能對每個狀態正向BFS,那樣在多case的情況下肯定是TLE的,另外就是要仔細看題,理解題目的意思,對題目的理解如果錯誤,將會導致思路的定式,覺得自己肯定是對的,這樣,在比賽的時候就會心慌,嚴重影響比賽的狀態。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.