Fliptile——搜索+二进制优化
【題目描述】
Farmer John knows that an intellectually satisfied cow is a happy cow who will give more milk. He has arranged a brainy activity for cows in which they manipulate an M × N grid (1 ≤ M ≤ 15; 1 ≤ N ≤ 15) of square tiles, each of which is colored black on one side and white on the other side.
As one would guess, when a single white tile is flipped, it changes to black; when a single black tile is flipped, it changes to white. The cows are rewarded when they flip the tiles so that each tile has the white side face up. However, the cows have rather large hooves and when they try to flip a certain tile, they also flip all the adjacent tiles (tiles that share a full edge with the flipped tile). Since the flips are tiring, the cows want to minimize the number of flips they have to make.Help the cows determine the minimum number of flips required, and the locations to flip to achieve that minimum. If there are multiple ways to achieve the task with the minimum amount of flips, return the one with the least lexicographical ordering in the output when considered as a string. If the task is impossible, print one line with the word "IMPOSSIBLE".Input
Line 1: Two space-separated integers: M and N
Lines 2… M+1: Line i+1 describes the colors (left to right) of row i of the grid with N space-separated integers which are 1 for black and 0 for white
Output
Lines 1… M: Each line contains N space-separated integers, each specifying how many times to flip that particular location.
Sample Input
Sample Output
0 0 0 0 1 0 0 1 1 0 0 1 0 0 0 0【題目分析】
看完題目后很明顯應(yīng)該是一個(gè)暴力搜索,但是應(yīng)該從哪里開始搜索呢?從頭開始的話會(huì)有215*15種可能,顯然是不允許的。我們應(yīng)該優(yōu)化一下搜索的順序,即哪些情況是顯然不可能成立的。
我們?nèi)绻麖纳贤滤阉?#xff0c;那么下面的對(duì)上面的影響只有四個(gè)方向中上面的那個(gè),那么如果搜索在x行,那么x-1行中的1下面的那塊必須翻轉(zhuǎn),0下面的那塊不能翻轉(zhuǎn)。這樣類推,我們發(fā)現(xiàn)除了第一行其他行的翻轉(zhuǎn)情況都已經(jīng)被確定,因此我們只需要枚舉第一行的翻轉(zhuǎn)情況(215種)就可以了。
看大佬的博客發(fā)現(xiàn)用到一種二進(jìn)制的優(yōu)化。如果沒有這種優(yōu)化的話我們可能需要搜索,相對(duì)比較復(fù)雜。
我們可以將一行中翻轉(zhuǎn)的情況看做一個(gè)數(shù),例如:110就是翻轉(zhuǎn)前兩個(gè),那么總共的情況就是1<<m種
對(duì)于一個(gè)數(shù)字,我們?nèi)绾慰焖倥袛嗄男┪皇?呢?
我們可以用110與100,010,001的與判斷,如果與的結(jié)果是0則該位是0,如果結(jié)果不是0則該位是1
有上面的方法后我們就可以寫出程序啦
【AC代碼】(借鑒大佬)
總結(jié)
以上是生活随笔為你收集整理的Fliptile——搜索+二进制优化的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 哥谭第二季剧情介绍
- 下一篇: Shuffle'm Up——简单模拟