本质上就是八皇后问题然后枚举最大值就行了
添加链接描述
#include<iostream>
#include<cstdio>
using namespace std;
bool chess[100][8][8];
int cnt;
bool temp[8][8];
bool leftd[15];
bool rightd[15];
bool jud[8];
int score[8][8];
void copy() {
for (int i = 0; i < 8; i++)
for (int j = 0; j < 8; j++)
chess[cnt][i][j] = temp[i][j];
cnt++;
}
void dfs(int n) {
if (n == 8) {
copy();
return ;
}
for(int i=0;i<8;i++)
if (!jud[i] && !leftd[7 + (n - i)] && !rightd[n + i]) {
jud[i] = true;
leftd[7 + (n - i)] = true;
rightd[n + i] = true;
temp[n][i] = true;
dfs(n + 1);
jud[i] = false;
leftd[7 + (n - i)] = false;
rightd[n + i] = false;
temp[n][i] = false;
}
}
int main() {
int n;
int i, j, k;
int sum;
int temp;
dfs(0);
cin >> n;
while (n--) {
sum = 0;
for (int i = 0; i < 8; i++)
for (int j = 0; j < 8; j++) {
scanf("%d",&score[i][j]);
}
for ( k= 0; k < cnt; k++) {
temp = 0;
for (i = 0; i < 8; i++) {
for (j = 0; j < 8; j++)
temp += score[i][j] * chess[k][i][j];
}
sum = sum > temp ? sum : temp;
}
printf("%5d\n", sum);
}
}