BZOJ#1085[SCOI2005]骑士精神
作者:互联网
[SCOI2005]骑士精神
思路:
迭代加深,启发式剪枝
代码:
#include <bits/stdc++.h>
#define int long long
int _ = 0, Case = 1;
using namespace std;
#define all(v) begin(v),end(v)
#define nline '\n'
const int N = 10;
int d[N][N];
int a[N][N];
int b[N][N];
void init() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
d[i][j] = 1;
}
}
for (int i = 2; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
d[i][j] = 0;
}
}
d[2][2] = 1;
d[3][3] = 2;
}
int dx[] = {1, 1, 2, 2, -2, -2, -1, -1};
int dy[] = {2, -2, 1, -1, 1, -1, 2, -2};
int check() {
int cnt = 0;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
cnt += (b[i][j] != d[i][j]);
}
}
return cnt;
}
bool dfs(int x, int y, int cur, int depth) {
int t = check();
if (!t) return true;
if (cur - 1 + t > depth) return false;
for (int i = 0; i < 8; i++) {
int tx = dx[i] + x, ty = y + dy[i];
if (tx >= 1 and tx <= 5 and ty >= 1 and ty <= 5) {
swap(b[x][y], b[tx][ty]);
if (dfs(tx, ty, cur + 1, depth)) return true;
swap(b[x][y], b[tx][ty]);
}
}
return false;
}
void solve(int Case) {
int x, y;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
char ch;
cin >> ch;
if (ch == '*') {
x = i, y = j;
a[i][j] = 2;
} else {
a[i][j] = ch - '0';
}
}
}
memcpy(b, a, sizeof b);
for (int i = 0; i <= 15; i++) {
if (dfs(x, y, 0, i)) {
cout << i << nline;
return;
}
memcpy(b, a, sizeof b);
}
cout << -1 << nline;
}
signed main() {
init();
ios::sync_with_stdio(false); cin.tie(nullptr);
cin >> _; for (Case = 1; Case <= _; Case++)
solve(Case);
return 0;
}
标签:Case,1085,ch,tx,int,SCOI2005,define,BZOJ 来源: https://www.cnblogs.com/koto-k/p/16095410.html