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
4 4
1 0 0 1
0 1 1 0
0 1 1 0
1 0 0 1
Sample Output
0 0 0 0
1 0 0 1
1 0 0 1
0 0 0 0
思路:不知道為啥這道題目會(huì)放在搜索專題上,可能搜索的方法也可以解決吧。
首先我們看數(shù)據(jù)量,最大是15.狀壓的一個(gè)很明顯的特點(diǎn)就是數(shù)據(jù)量小。我們?nèi)绻凑毡┝Φ姆椒ǖ脑?#xff0c;數(shù)據(jù)量就特別大,肯定會(huì)超時(shí)。那么我們就將第一行是否翻轉(zhuǎn)的情況枚舉一下。
假如是m列的話,我們枚舉0~(2^m-1)的數(shù)字,轉(zhuǎn)換成二進(jìn)制,就是01串。vis[i][j]=0就是不翻轉(zhuǎn),vis[i][j]=1代表翻轉(zhuǎn)。
我們枚舉了第一行的翻轉(zhuǎn)情況,然后從第二行開(kāi)始,如果該位置的上一個(gè)位置是黑色的話,這一個(gè)位置,是必須要翻轉(zhuǎn)的。翻轉(zhuǎn)完成之后,如果最后一行全是白色的話,就說(shuō)明第一行的翻轉(zhuǎn)是可行的,記錄一下最小值。
題目要求字典序最小,我們枚舉的順序正好滿足了字典序最小。
這是轉(zhuǎn)換成二進(jìn)制串的代碼,結(jié)果如圖所示:
代碼如下:
努力加油a啊
總結(jié)
以上是生活随笔為你收集整理的Fliptile(状压+思维)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 那些银行可以办理etc 什么银行能够办理
- 下一篇: AT1350 深さ優先探索(洛谷 深度优