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
思路:不知道為啥這道題目會放在搜索專題上,可能搜索的方法也可以解決吧。
首先我們看數據量,最大是15.狀壓的一個很明顯的特點就是數據量小。我們如果按照暴力的方法的話,數據量就特別大,肯定會超時。那么我們就將第一行是否翻轉的情況枚舉一下。
假如是m列的話,我們枚舉0~(2^m-1)的數字,轉換成二進制,就是01串。vis[i][j]=0就是不翻轉,vis[i][j]=1代表翻轉。
我們枚舉了第一行的翻轉情況,然后從第二行開始,如果該位置的上一個位置是黑色的話,這一個位置,是必須要翻轉的。翻轉完成之后,如果最后一行全是白色的話,就說明第一行的翻轉是可行的,記錄一下最小值。
題目要求字典序最小,我們枚舉的順序正好滿足了字典序最小。
這是轉換成二進制串的代碼,結果如圖所示:
代碼如下:
努力加油a啊
總結
以上是生活随笔為你收集整理的Fliptile(状压+思维)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 那些银行可以办理etc 什么银行能够办理
- 下一篇: 二套房贷利率是多少2022,基准利率上涨