[BZOJ 1085] [SCOI2005] 骑士精神 [ IDA* 搜索 ]
生活随笔
收集整理的這篇文章主要介紹了
[BZOJ 1085] [SCOI2005] 骑士精神 [ IDA* 搜索 ]
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
題目鏈接 : BZOJ 1085
?
題目分析 :
本題中可能的狀態會有 (2^24) * 25 種狀態,需要使用優秀的搜索方式和一些優化技巧。
我使用的是 IDA* 搜索,從小到大枚舉步數,每次 DFS 驗證在當前枚舉的步數之內能否到達目標狀態。
如果不能到達,就枚舉下一個步數,重新搜索,即使某些狀態在之前的 DFS 中已經搜索過,我們仍然搜索。
并且在一次 DFS 中,我們不需要判定重復的狀態。
在 IDA* 中,重要的剪枝優化是?估價函數?,將一些不可能存在可行解的枝條剪掉。
如果估價函數寫得高效,就能有極好的效果。我們寫估價函數的原則是,絕對不能剪掉可能存在可行解的枝條。
因此,在預估需要步數時,應讓估計值盡量接近實際步數,但一定不能大于實際需要的步數。
本題的一個很有效的估價函數是,比較當前狀態的黑白騎士與目標狀態的黑白騎士有多少不同,我們把這個值作為估價函數值,因為每一步最多將當前狀態的一個騎士改變為與目標狀態相同。但是應該注意的是,空格所在的格子不要算入其中。
?
代碼如下:
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <algorithm>using namespace std;const int MaxStep = 15; const int Dx[8] = {1, 1, -1, -1, 2, 2, -2, -2}, Dy[8] = {2, -2, 2, -2, 1, -1, 1, -1};int Te, Ans;char Str[6];struct ES {int num, pos;bool operator == (const ES &e) const {return (num == e.num) && (pos == e.pos);} } S, T;inline bool Inside(int x, int y) {if (x < 0 || x > 4) return false;if (y < 0 || y > 4) return false;return true; }void Print(ES x) {for (int i = 0; i < 5; ++i) {for (int j = 0; j < 5; ++j) {if (x.pos == (i * 5 + j)) printf("*");else {if (x.num & (1 << (i * 5 + j))) printf("1");else printf("0");}}printf("\n");} }inline int Expect(ES x) {int Temp, Cnt;Temp = x.num ^ T.num;Cnt = 0;if (x.pos != T.pos) {if (Temp & (1 << T.pos)) --Cnt;if (Temp & (1 << x.pos)) --Cnt;}while (Temp) {++Cnt;Temp -= Temp & -Temp;}return Cnt; }bool DFS(ES Now, int Step, int Limit) {if (Now == T) return true;if (Step == Limit) return false;if (Expect(Now) > Limit - Step) return false;int x, y, xx, yy;ES Next;x = Now.pos / 5; y = Now.pos % 5;for (int i = 0; i < 8; i++) {xx = x + Dx[i]; yy = y + Dy[i];if (!Inside(xx, yy)) continue;Next = Now; Next.pos = xx * 5 + yy;Next.num &= (1 << 25) - 1 - (1 << (xx * 5 + yy));if (Now.num & (1 << (xx * 5 + yy))) Next.num |= (1 << (x * 5 + y)); if (DFS(Next, Step + 1, Limit)) return true;}return false; }int IDAStar(ES S) {if (S == T) return 0;for (int i = 1; i <= MaxStep; ++i) if (DFS(S, 0, i)) return i;return -1; }int main() {scanf("%d", &Te);T.num = 549855; T.pos = 12;for (int Case = 1; Case <= Te; ++Case) {S.num = 0;for (int i = 0; i < 5; ++i) {scanf("%s", Str);for (int j = 0; j < 5; ++j) {if (Str[j] == '1') S.num |= (1 << (i * 5 + j));if (Str[j] == '*') S.pos = i * 5 + j;}}Ans = IDAStar(S);printf("%d\n", Ans);} return 0; }
?
轉載于:https://www.cnblogs.com/JoeFan/p/4160896.html
總結
以上是生活随笔為你收集整理的[BZOJ 1085] [SCOI2005] 骑士精神 [ IDA* 搜索 ]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 记一次代码被公司电脑加密后,编译不通过
- 下一篇: 全国计算机等级考试题库二级C操作题100