题解:P17183 [ICPC 2017 Hong Kong R] Equivalence of Sudoku
Wangruofan · · 题解
P17183 [ICPC 2017 Hong Kong R] Equivalence of Sudoku
题意
定义:一个数独解是一个
可以对一个矩阵进行如下任意次变换:
如果一个矩阵可以由另一个矩阵通过如上变换得到,则称它们为等价的。
两个矩阵
题目给定
思路
对于一个正方形进行变换,最终只会得到
考虑到
那么如何判断两个矩阵的关系呢?
假设目前要判定
- 若
a_{i,j} \ne 0 且b_{i,j} = 0 :a 存在独有线索无法匹配,该变换不合法。 - 若
a_{i,j} = 0 :无约束,直接跳过。 - 若
a_{i,j},b_{i,j} 均非0 :- 若数字
a_{i,j} 已有映射:校验是否等于当前b_{i,j} ,冲突则非法。 - 若无映射:若
b_{i,j} 未被占用,建立a_{i,j} \to b_{i,j} 的双向映射;否则非法。
- 若数字
若整图校验完全无冲突,则
笔者赛时这个函数调了半个小时。
判定
判定
若以上情况都不符合,即是无法比较。
代码
#include<iostream>
#include<string.h>
using namespace std;
const int N=409;
int a[N][10][10];
int cnt[N],n;
int ans[N][N];//E,L,G,I
int to[10],vst[10];
void print(const int a[10][10]){
for(int i=1;i<=9;++i){
for(int j=1;j<=9;++j){
cout<<a[i][j]<<" ";
}
cout<<endl;
}
}
void R(int a[10][10],int (&b)[10][10]){
//rotate 90 degree
for(int i=1;i<=9;++i){
for(int j=1;j<=9;++j){
b[j][10-i]=a[i][j];
}
}
}
void Mx(int (&a)[10][10]){
//use swap to flip along x
for(int i=1;i<=9;++i){
for(int j=1;j<=4;++j){
swap(a[i][j],a[i][10-j]);
}
}
}
bool checkL(const int a[10][10],const int b[10][10]){
memset(to,0,sizeof to);
memset(vst,0,sizeof vst);
for(int i=1;i<=9;++i){
for(int j=1;j<=9;++j){
if(a[i][j]!=0&&b[i][j]==0){
return 0;
}
if(a[i][j]==0) continue;
if(to[a[i][j]]==0){
if(vst[b[i][j]]){
return 0;
}
to[a[i][j]]=b[i][j];
vst[b[i][j]]=1;
}
else{
if(to[a[i][j]]!=b[i][j]){
return 0;
}
}
}
}
return 1;
}
bool checkG(const int a[10][10],const int b[10][10]){
return checkL(b,a);
}
bool checkE(const int a[10][10],const int b[10][10]){
return checkL(a,b)&&checkL(b,a);
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cin>>n;
for(int i=1;i<=n;++i){
for(int j=1;j<=9;++j){
for(int k=1;k<=9;++k){
cin>>a[i][j][k];
}
}
}
for(int i=1;i<n;++i){
for(int j=i+1;j<=n;++j){
int t[10][10],A[10][10];//A为原版,t为变换后的
for(int k=1;k<=9;++k){
for(int l=1;l<=9;++l){
A[k][l]=t[k][l]=a[j][k][l];
}
}
for(int rot=1;rot<=4;++rot){
R(A,t);
for(int k=1;k<=2;++k){
Mx(t);
if(checkE(a[i],t)){
ans[j][i]=ans[i][j]=1;
goto end;
}
if(checkL(a[i],t)){
ans[i][j]=2;
ans[j][i]=3;
goto end;
}
if(checkG(a[i],t)){
ans[i][j]=3;
ans[j][i]=2;
goto end;
}
}
for(int k=1;k<=9;++k){
for(int l=1;l<=9;++l){
A[k][l]=t[k][l];
}
}
}
end:
if(ans[i][j]==0) ans[i][j]=ans[j][i]=4;
}
}
for(int i=1;i<=n;++i){
for(int j=1;j<=n;++j){
if(i==j){
putchar('E');
continue;
}
if(ans[i][j]==1) putchar('E');
else if(ans[i][j]==2) putchar('L');
else if(ans[i][j]==3) putchar('G');
else if(ans[i][j]==4) putchar('I');
}
putchar('\n');
}
return 0;
}