您的位置:首页 > 其它

UVA 11464 暴力+位运算 ***

2015-10-24 19:59 453 查看
题意:给你一个 n * n 的 01 矩阵,现在你的任务是将这个矩阵中尽量少的 0 转化为 1 ,使得每个数的上下左右四个相邻的数加起来是偶数。求最少的转化个数。

新风格代码

lrj书上说的很清楚了,就是判断下一行的代码有点冗余了,但是很好理解,就是模拟每位有的数字之和,然后判断未知为应该填的数字

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#include<map>
using namespace std;
#define MOD 1000000007
const int INF=0x3f3f3f3f;
const double eps=1e-5;
typedef long long ll;
#define cl(a) memset(a,0,sizeof(a))
#define ts printf("\n*****\n");
#define sc(a) scanf("%d",&a);
#define pt(a) printf("%d\n",a);
const int MAXN=25;

//define single variable

int n,m,tt;
int ans,sum,sum1,sum2,tot,Max;

//define arrays
int a[MAXN][MAXN],b[MAXN][MAXN];
char s[MAXN];
int vis[MAXN];
//define struct
struct Node
{
int x,y;
Node(){}
/*Node(int xx,int yy,int tt)
{

}*/
void in()
{
scanf("%d%d",&x,&y);
}
}node[MAXN];

//others
bool cmp(Node a,Node b)
{
return a.y>b.y;
}

void init()
{
ans=INF,sum=0,sum1=0,sum2=0,tot=0,Max=0;
//cl(vis);
//cl(node);
cl(a),cl(b);
}

int check(int st)
{
//printf("st:  %d\n",st);
cl(b);
int w=0;
int i,j,k;
for(i=0;i<n;i++)
{
if(st&(1<<i))
{
b[0][i]=1;
}
else b[0][i]=0;
}
/*for(i=0;i<n;i++)
{
printf("%d ",b[0][i]);
}
printf("\n");*/
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(a[i][j]==1&&b[i][j]==0)     return INF;  //注意只能由0变成1,不能从1变成0
w=0;
if(i==0)    //在顶层
{
if(j==0)    //在顶层左上角
{
w=b[i][j+1];
}
else if(j==n-1) //顶层右上角
{
w=b[i][j-1];
}
else w=b[i][j-1]+b[i][j+1];
}
else if(i==n-1)
{
if(j==0)
{
w=b[i][j+1]+b[i-1][j];
}
else if(j==n-1)
{
w=b[i-1][j]+b[i][j-1];
}
else w=b[i-1][j]+b[i][j+1]+b[i][j-1];
if(w%2!=0)  return INF;
}
else
{
if(j==0)
{
w=b[i-1][j]+b[i][j+1];
}
else if(j==n-1)
{
w=b[i-1][j]+b[i][j-1];
}
else
{
w=b[i-1][j]+b[i][j-1]+b[i][j+1];
}
}
b[i+1][j]=w%2==0?0:1;
}
}
/*ts
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d ",b[i][j]);
}
printf("\n");
}
ts*/
int cnt=0;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
if(a[i][j]!=b[i][j])    cnt++;
}
return cnt;
}

int main()
{
int i,j,k,ca=1;
#ifndef ONLINE_JUDGE
freopen("1.in","r",stdin);
#endif

scanf("%d",&tt);
while(tt--)
{
printf("Case %d: ",ca++);
init();
sc(n)
for(i=0;i<n;i++)
for(j=0;j<n;j++)
sc(a[i][j])
for(i=0;i<(1<<n);i++)
{
ans=min(ans,check(i));
}
if(ans==INF)    ans=-1;
pt(ans)
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: