UVA 11464 - Even Parity
2015-10-01 15:11
281 查看
该题也是一个需要观察和等价转换思维的题目。 如果直接暴力,时间复杂度难以承受,但是其实我们可以发现,只需要枚举第一行就可以了,只要第一行确定了,那么最终的偶数矩阵也就确定了,可以利用偶数限制关系轻松推出其他的格子,在这个过程中判断是否符合规则即可。
细节参见代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int INF = 10000000;
const int maxn = 20 + 5;
int T,n,m,ans,kase = 0,cur,a[maxn][maxn];
bool check(int S) {
int vis[maxn][maxn];
for(int i = 0; i < n; i++) {
if(S & (1 << i)) {
if(a[1][i+1] == 0) cur++;
vis[1][i+1] = 1;
}
else {
if(a[1][i+1]) return false;
vis[1][i+1] = 0;
}
}
for(int i = 2; i <= n; i++) {
for(int j = 1; j <= n; j++) {
int v = 0;
if(j > 1) v += vis[i-1][j-1];
if(j < n) v += vis[i-1][j+1];
if(i-1 > 1) v += vis[i-2][j];
if(v & 1) vis[i][j] = 1;
else vis[i][j] = 0;
if(a[i][j] == 1 && vis[i][j] == 0) return false;
if(a[i][j] == 0 && vis[i][j] == 1) cur++;
}
}
return true;
}
int main() {
scanf("%d",&T);
while(T--) {
scanf("%d",&n);
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
scanf("%d",&a[i][j]);
ans = INF;
for(int i = 0; i < (1 << n); i++) {
cur = 0;
if(check(i)) ans = min(ans,cur);
}
printf("Case %d: %d\n",++kase,(ans == INF ? -1 : ans));
}
return 0;
}
细节参见代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int INF = 10000000;
const int maxn = 20 + 5;
int T,n,m,ans,kase = 0,cur,a[maxn][maxn];
bool check(int S) {
int vis[maxn][maxn];
for(int i = 0; i < n; i++) {
if(S & (1 << i)) {
if(a[1][i+1] == 0) cur++;
vis[1][i+1] = 1;
}
else {
if(a[1][i+1]) return false;
vis[1][i+1] = 0;
}
}
for(int i = 2; i <= n; i++) {
for(int j = 1; j <= n; j++) {
int v = 0;
if(j > 1) v += vis[i-1][j-1];
if(j < n) v += vis[i-1][j+1];
if(i-1 > 1) v += vis[i-2][j];
if(v & 1) vis[i][j] = 1;
else vis[i][j] = 0;
if(a[i][j] == 1 && vis[i][j] == 0) return false;
if(a[i][j] == 0 && vis[i][j] == 1) cur++;
}
}
return true;
}
int main() {
scanf("%d",&T);
while(T--) {
scanf("%d",&n);
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
scanf("%d",&a[i][j]);
ans = INF;
for(int i = 0; i < (1 << n); i++) {
cur = 0;
if(check(i)) ans = min(ans,cur);
}
printf("Case %d: %d\n",++kase,(ans == INF ? -1 : ans));
}
return 0;
}
相关文章推荐
- 1.10055 - Hashmat the brave warrior
- 2.10071 - Back to High School Physics
- 3.458 - The Decoder
- 4.694 - The Collatz Sequence
- 6.494 - Kindergarten Counting Game
- 7.490 - Rotating Sentences
- 8.414 - Machined Surfaces
- 9.488 - Triangle Wave
- A.457 - Linear Cellular Automata
- B.489 - Hangman Judge
- C.445 - Marvelous Mazes
- 1.10494 - If We Were a Child Again
- 2.424 - Integer Inquiry
- 3.10250 - The Other Two Trees
- 5.465 - Overflow
- 6.113 - Power of Cryptography
- 7.10161 - Ant on a Chessboard
- 8.621 - Secret Research
- 9.401 - Palindromes
- A.537 - Artificial Intelligence?