Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 5719 | Accepted: 2162 |
Description
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
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
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
Source
kuangbin带你飞 专题1 D题
感觉这个题有点神。。。
题意就是 给你m*n的矩阵 有0 有1 需要把所有1翻转成0
每次选i,j翻转 会同时翻转i-1,j i+1,j i,j-1 i,j+1
问次数最少的方案
如果有多种 输出字典序最小的
首先每个位置最多翻一次,因为翻两次和没翻效果是一样的
但是想把第一排全变成0 可以由第一排翻转 也可以由第二排翻转 所以不太好做
于是可以枚举第一排的反转情况 第一排翻转完成后 想让第一排全变成0 只能通过翻转第二排的某几个
同时第二排也确定了 只能翻转第三排
就可以推出来所有的应该翻转的情况了
然后最后一排反转情况确定了 最后的翻转完成情况就确定了 如果最后一排全是0 那么是一个可行方案 否则不可行
按字典序枚举第一排翻转情况 能保证答案是按字典序排列的
然后记录翻转次数
次数小于时更新答案
金大爷太神辣!
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int mx[5]={0,1,0,-1,0};
const int my[5]={0,0,1,0,-1};
int f[22][22];
int m,n;
int cz[22][22];
int ok;
int t[22][22];
int ans;
int p[22][22];
void work(int x,int y)
{
for(int i=0;i<=4;i++)
{
int xx=x+mx[i],yy=y+my[i];
t[xx][yy]^=1;
}
}
int test()
{
int ret=0;
for(int i=1;i<=n;i++)
if(cz[1][i])
ret++;
for(int i=2;i<=m;i++)
for(int j=1;j<=n;j++)
if(t[i-1][j]==1)
{
cz[i][j]=1;
work(i,j);
ret++;
}
else
cz[i][j]=0;
for(int i=1;i<=n;i++)
if(t[m][i]!=0)
return -1;
return ret;
}
void dfs(int dep)
{
if(dep==n+1)
{
memcpy(t,f,sizeof(f));
for(int i=1;i<=n;i++)
if(cz[1][i])
work(1,i);
int k=test();
if(k!=-1)
{
if(k<ans)
{
ans=k;
memcpy(p,cz,sizeof(cz));
}
}
return;
}
for(int i=0;i<=1;i++)
{
cz[1][dep]=i;
dfs(dep+1);
}
}
int main()
{
while(scanf("%d%d",&m,&n)==2)
{
ans=0x3f3f3f3f;
for(int i=1;i<=m;i++)
for(int j=1;j<=n;j++)
scanf("%d",&f[i][j]);
dfs(1);
if(ans!=0x3f3f3f3f)
{
for(int i=1;i<=m;i++)
{
for(int j=1;j<=n;j++)
printf("%d ",p[i][j]);
printf("\n");
}
}
else
{
printf("IMPOSSIBLE\n");
}
}
return 0;
}