a519中等枚舉92個八皇后解與位置差異
CPE:Back to the 8-Queens (UVa 11085)
把最少移動問題轉成對所有合法目標的最小漢明距離。
解題思路
每欄始終一個皇后,而且只能在原欄上下移,所以任何合法目標與輸入的差異欄數,就是到該目標所需的移動數。先回溯枚舉所有八皇后解:逐欄選列,若與前面任一皇后同列,或列差絕對值等於欄差,就剪枝。
八欄填完即得到一個合法排列,總共92個,預先保存供所有測資共用。每筆對這些解計算八個位置中有多少不同,取最小值即可,原本已合法時為0。輸入沒有測試筆數,讀到EOF,每8個整數為一組,輸出Case k: M。
Step-by-step animation
示意:輸入1,5,8,6,3,7,2,5,對照合法解1,5,8,6,3,7,2,4
步驟 1 / 3
比較前四欄
1、5、8、6都與合法目標相同,不需移動。
1=1
5=5
8=8
6=6
- 已比較欄數
- 4
- 移動數
- 0
#include <iostream>
#include <vector>
#include <array>
#include <cstdlib>
#include <algorithm>
using namespace std;
vector<array<int, 8>> solutions;
array<int, 8> board;
void generate(int col) {
if (col == 8) {
solutions.push_back(board);
return;
}
for (int row = 1; row <= 8; ++row) {
bool ok = true;
for (int j = 0; j < col; ++j)
if (board[j] == row || abs(board[j] - row) == col - j)
ok = false;
if (ok) {
board[col] = row;
generate(col + 1);
}
}
}
int main() {
generate(0);
array<int, 8> input;
int tc = 0;
while (cin >> input[0]) {
for (int i = 1; i < 8; ++i)
cin >> input[i];
int answer = 8;
for (const auto &target : solutions) {
int cost = 0;
for (int i = 0; i < 8; ++i)
cost += (input[i] != target[i]);
answer = min(answer, cost);
}
cout << "Case " << ++tc << ": " << answer << '\n';
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。