原题AtCoder Regular Contest 095E - Symmetric Grid,在这里膜xyx大神,之前看了篇所谓的题解其实是暴力,照着写到一半发现不太对,跑了数据果然t飞,然后滚回去看std。
一道搜索题,先预处理出行与行和列与列是否能匹配的关系,然后先枚举行的最终排列,再将列两两匹配。注意奇数的情况。
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 15;
template <typename T> void chkmax(T &x, T y) {x = max(x, y); }
template <typename T> void chkmin(T &x, T y) {x = min(x, y); }
template <typename T> void read(T &x) {
x = 0; int f = 1;
char c = getchar();
for (; !isdigit(c); c = getchar()) if (c == '-') f = -f;
for (; isdigit(c); c = getchar()) x = x * 10 + c - '0';
x *= f;
}
template <typename T> void write(T x) {
if (x < 0) x = -x, putchar('-');
if (x > 9) write(x / 10);
putchar(x % 10 + '0');
}
template <typename T> void writeln(T x) {
write(x);
puts("");
}
int n, m;
char mp[MAXN][MAXN];
int rnum[MAXN], cnum[MAXN];
bool visrow[MAXN], viscol[MAXN];
bool row[MAXN][MAXN], col[MAXN][MAXN];
void check(){
for(int i=1;i<= n;i++)
for(int j=1;j<= m;j++)
if(mp[rnum[i]][cnum[j]]!=mp[rnum[n-i+1]][cnum[m-j+1]])return;
printf("YES\n");
exit(0);
}
void workc(int pos,int type){
if(pos==0){
check();
return;
}
if(type){
for(int i=1;i<=m;i++){
viscol[i]=true;
cnum[pos]=i;
workc(pos-1,0);
viscol[i]=false;
}
}
else{
for(int i=1;i<=m;i++){
if(viscol[i])continue;
for(int j=i+1;j<=m;j++)
if(!viscol[j]&&col[i][j]){
viscol[i]=true;
viscol[j]=true;
cnum[pos]=i;
cnum[m+1-pos]=j;
workc(pos-1,0);
viscol[i]=false;
viscol[j]=false;
}
return;
}
}
}//枚举列
void workr(int pos,int type){
if(pos==0){
workc((m+1)/2,m&1);
return;
}
if(type){
for(int i=1;i<=n;i++){
visrow[i]=true;
rnum[pos]=i;
workr(pos-1,0);
visrow[i]=false;
}
}
else{
for(int i=1;i<=n;i++){
if(visrow[i])continue;
for(int j=i+1;j<=n;j++)
if(!visrow[j]&&row[i][j]){
visrow[i]=true;
visrow[j]=true;
rnum[pos]=i;
rnum[n+1-pos]=j;
workr(pos-1,0);
visrow[i]=false;
visrow[j]=false;
}
return;
}
}
}//枚举行
int main(){
read(n),read(m);
for(int i=1;i<=n;i++)
scanf("%s",mp[i]+1);
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++){
static char x[MAXN],y[MAXN];
for(int k=1;k<=m;k++){
x[k]=mp[i][k];
y[k]=mp[j][k];
}
sort(x+1,x+m+1);
sort(y+1,y+m+1);
row[i][j]=true;
for(int k=1;k<=m;k++)
if(x[k]!=y[k])row[i][j]=false;
}//枚举行匹配
for(int i=1;i<=m;i++)
for(int j=1;j<=m;j++){
static char x[MAXN],y[MAXN];
for(int k=1;k<=n;k++){
x[k]=mp[k][i];
y[k]=mp[k][j];
}
sort(x+1,x+n+1);
sort(y+1,y+n+1);
col[i][j]=true;
for(int k=1;k<=n;k++)
if(x[k]!=y[k])col[i][j]=false;
}//枚举列匹配
workr((n+1)/2,n&1);
printf("NO\n");
return 0;
}