UVALive 6665 Dragon’s Cruller (BFS + 優先佇列+hash)
題目連結:傳送門
題意:
一個九宮格,給定你初始狀態和結束狀態,每次橫向移動和縱向移動都有一定的花費,
問從初始狀態到結束狀態的最小花費。
分析:
BFS,用優先佇列維護到達當前狀態的最優值,用hash判斷當前的狀態是否達到過。
程式碼如下:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;
const int INF = 1e9+7777;
int fac[9]= {1,1,2,6,24,120,720,5040,40320}; //康託展開,用來hash
struct nod {
int mp[9],pos,cost;
bool operator <(const struct nod &tmp)const {
return this->cost > tmp.cost;
}
} P;
int dx[4]= {1,-1,0,0};
int dy[4]= {0,0,-1,1};
int s[9],e[9];
int cv,ch;
int vis[40320*9+100];
int getHashVal(int *a) { //hash得到hash值。
int val = 0;
for(int i=0; i<9; i++) {
int cnt=0;
for(int j=0; j<i; j++) cnt+=(a[j]>a[i]);
val+=cnt*fac[i];
}
return val;
}
bool check(nod tmp) {
int cnt = 0;
for(int i=0; i<9; i++)
cnt+=(tmp.mp[i]==e[i]);
return cnt==9;
}
int BFS(nod st) {
priority_queue<nod> Q;
Q.push(st);
vis[getHashVal(st.mp)]=0;
while(!Q.empty()) {
nod top = Q.top();
Q.pop();
if(check(top)) {
return top.cost;
}
for(int i=0; i<4; i++) {
int tmppos = top.pos;
int nowx = (top.pos/3+dx[i]+3)%3;//轉換
int nowy = top.pos%3+dy[i];
if(nowy==3){
nowy=0;
nowx=(nowx+1)%3;
}
if(nowy==-1){
nowy=2;
nowx=(nowx-1+3)%3;
}
swap(top.mp[nowx*3+nowy],top.mp[tmppos]);
if(i<2) top.cost+=cv;
else top.cost+=ch;
top.pos=nowx*3+nowy;
int val = getHashVal(top.mp);
if(top.cost<vis[val]) {
Q.push(top);
vis[val]=top.cost;
}
swap(top.mp[nowx*3+nowy],top.mp[tmppos]);
if(i<2) top.cost-=cv;
else top.cost-=ch;
top.pos=tmppos;
}
}
}
nod init() {
nod st;
for(int i=0; i<40320*9+100; i++) vis[i]=INF;
for(int i=0; i<9; i++) {
st.mp[i]=s[i];
if(s[i]==0) st.pos=i;
}
st.cost=0;
return st;
}
int main() {
while(~scanf("%d%d",&ch,&cv)) {
if(cv==0&&ch==0) break;
for(int i=0; i<9; i++) scanf("%d",s+i);
for(int i=0; i<9; i++) scanf("%d",e+i);
printf("%d\n",BFS(init()));
}
return 0;
}
/*
4 9
6 3 0
8 1 2
4 5 7
6 3 0
8 1 2
4 5 7
31 31
4 3 6
0 1 5
8 2 7
0 3 6
4 1 5
8 2 7
92 4
1 5 3
4 0 7
8 2 6
1 5 0
4 7 3
8 2 6
12 28
3 4 5
0 2 6
7 1 8
5 7 1
8 6 2
0 3 4
0
31
96
312
*/
相關文章
- hdu5040 優先佇列+bfs佇列
- 【BFS+優先佇列】HDU 3442 Three Kingdoms佇列
- acmdream1191 bfs+優先佇列ACM佇列
- HDU 1026(優先佇列+BFS+前驅記錄)佇列
- PHP優先佇列PHP佇列
- 堆--優先佇列佇列
- 優先佇列 (轉)佇列
- 淺談優先佇列佇列
- STL 優先佇列 用法佇列
- 堆與優先佇列佇列
- 堆和優先佇列佇列
- 優先佇列和堆排序佇列排序
- 堆排序與優先佇列排序佇列
- Java優先佇列(PriorityQueue)示例Java佇列
- 01揹包優先佇列優化佇列優化
- 棧,佇列,優先順序佇列簡單介面使用佇列
- Redis實現任務佇列、優先順序佇列Redis佇列
- NO GAME NO LIFE(優先佇列/最小堆)GAM佇列
- 優先佇列的比較器佇列
- 封裝優先順序佇列封裝佇列
- 二叉堆優先佇列佇列
- POJ 3253 Fence Repair 優先佇列AI佇列
- 堆——神奇的優先佇列(上)佇列
- 優先佇列的效能測試佇列
- 佇列 優先順序佇列 python 程式碼實現佇列Python
- 演算法面試(三) 優先佇列演算法面試佇列
- STL優先佇列最小堆最大堆佇列
- STL醜數(set+優先佇列)佇列
- 【圖論】拓撲排序+優先佇列圖論排序佇列
- 1007(優先佇列)佇列
- POJ 1724 ROADS(優先佇列+spfa)佇列
- POJ2431 Expedition (優先佇列)佇列
- POJ 2051(最小堆/優先佇列)佇列
- 三、資料結構演算法-棧、佇列、優先佇列、雙端佇列資料結構演算法佇列
- hdu5336 多校聯合第四場1010 模擬+bfs優先佇列佇列
- .NET 6 優先佇列 PriorityQueue 實現分析佇列
- Java優先順序佇列DelayedWorkQueue原理分析Java佇列
- C++ STL 優先佇列 (priority_queue)C++佇列