1. 程式人生 > >八屆藍橋杯: 2 標題:跳蚱蜢

八屆藍橋杯: 2 標題:跳蚱蜢

下標 != index style img pop names 就是 max

圖所示:
有9只盤子,排成1個圓圈。
其中8只盤子內裝著8只蚱蜢,有一個是空盤。
我們把這些蚱蜢順時針編號為 1~8


每只蚱蜢都可以跳到相鄰的空盤中,
也可以再用點力,越過一個相鄰的蚱蜢跳到空盤中。


請你計算一下,如果要使得蚱蜢們的隊形改為按照逆時針排列,
並且保持空盤的位置不變(也就是1-8換位,2-7換位,...),至少要經過多少次跳躍?

技術分享圖片

註意:要求提交的是一個整數,請不要填寫任何多余內容或說明文字。

思想是bfs廣搜,為了節省內存,使用 int 來存儲數據,之前用的是string類型以及string類型的數組存放數據,但是太容易超內存,而且判重過程算的太慢,看了這位大神的代碼,恍然大悟,可以用 bool 類型的數組進行判重,s = 123456789當作數組下標,以下是我稍作修改的代碼,可能看起來更簡潔吧!

#include <iostream>
#include <queue>
#define Maxn 1000000000
 
using namespace std;
 
int s = 123456789,t = 876543219;
 
int di[4] = {-2,-1,1,2},a[10];
 
bool index[Maxn];
 
int get_val(int *a)
{
    int sum=0;
    for(int i=0; i<9; i++)
    {
        sum*=10;
        sum+=a[i];
    }
    
return sum; } void bfs() { int find = 0; queue<int> q; queue<char> qu; //計算步數 q.push(s); index[s] = 1; qu.push(1); while(find != 1) { int x = q.front(),cnt=8,now; int count = qu.front(); while(x>0) //將數據存入數組,方便換位置
{ if(x%10==9)now=cnt; a[cnt--]=x%10; x/=10; } for(int i = 0; i<4; i++) { swap(a[now],a[(now+di[i]+9)%9]); int num = get_val(a); if(!index[num]) //判重 { if(num == t) { find = 1; cout<<count; } index[num] = 1; q.push(num); qu.push(count+1); } swap(a[now],a[(now+di[i]+9)%9]); } q.pop(); qu.pop(); } } int main() { bfs(); return 0; }

八屆藍橋杯: 2 標題:跳蚱蜢