题意:给出n*n的01矩阵,将尽量少的0变成1,使得每个元素的上下左右的元素的和为偶数
看的白书的思路,二进制枚举第一行,再依次算出改变元素的个数,
自己写的时候发现这里不会写,“每个元素的上下左右的元素”
大概就是这个意思
真是太捉急了的说-----------5555
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include <cmath> 5 #include<stack> 6 #include<vector> 7 #include<map> 8 #include<set> 9 #include<queue> 10 #include<algorithm> 11 using namespace std; 12 13 typedef long long LL; 14 const int INF = (1<<30)-1; 15 const int mod=1000000007; 16 const int maxn=1000005; 17 18 int n; 19 int a[55][55]; 20 int b[55][55]; 21 int ans; 22 23 int solve(int s){ 24 memset(b,0,sizeof(b)); 25 for(int c = 0; c < n;c++){ 26 if( s & (1<<c)) b[0][c] = 1; 27 else if(a[0][c] == 1) return INF; 28 } 29 30 for(int r = 1;r < n;r++){ 31 for(int c = 0;c < n;c++){ 32 int sum = 0; 33 if(r > 1) sum += b[r-2][c]; 34 if(c < n-1) sum += b[r-1][c+1]; 35 if(c > 0) sum += b[r-1][c-1]; 36 b[r][c] = sum % 2; 37 if(a[r][c] == 1 && b[r][c] == 0) return INF; 38 } 39 } 40 int cnt = 0; 41 for(int i = 0;i < n;i++){ 42 for(int j = 0;j < n;j++){ 43 if(a[i][j] != b[i][j]) cnt++; 44 } 45 } 46 return cnt; 47 } 48 49 int main(){ 50 int T; 51 scanf("%d",&T); 52 int kase = 0; 53 while(T--){ 54 memset(a,0,sizeof(a)); 55 scanf("%d",&n); 56 for(int i=0;i<n;i++) 57 for(int j=0;j<n;j++) scanf("%d",&a[i][j]); 58 59 ans = INF; 60 for(int s = 0;s < (1<<n); s++) ans = min(ans,solve(s)); 61 62 if(ans == INF) ans = -1; 63 printf("Case %d: %d\n",++kase,ans); 64 } 65 return 0; 66 }
加油啊~~~~
gooooooooooooo~~~~~~~~~~
时间: 2024-10-13 11:46:00