2017年第八届蓝桥杯 - 省赛 - C/C++大学A组 - B. 跳蚱蜢
生活随笔
收集整理的這篇文章主要介紹了
2017年第八届蓝桥杯 - 省赛 - C/C++大学A组 - B. 跳蚱蜢
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
如圖所示:
有9只盤子,排成1個圓圈。
其中8只盤子內裝著8只蚱蜢,有一個是空盤。
我們把這些蚱蜢順時針編號為 1~8
每只蚱蜢都可以跳到相鄰的空盤中,
也可以再用點力,越過一個相鄰的蚱蜢跳到空盤中。
請你計算一下,如果要使得蚱蜢們的隊形改為按照逆時針排列,
并且保持空盤的位置不變(也就是1-8換位,2-7換位,…),至少要經過多少次跳躍?
注意:要求提交的是一個整數,請不要填寫任何多余內容或說明文字。
代碼
#include <iostream> #include <cstring> #include <string> #include <cstdlib> #include <queue> #include <set> using namespace std; char *start="012345678"; char *target="087654321"; struct StateAndLevel {char *state;int level;int pos0;StateAndLevel(char *_state,int _level,int _pos0):state(_state),level(_level),pos0(_pos0){} }; struct cmp {bool operator()(char *a,char *b){return strcmp(a,b)<0;} }; void swap(char *s, int a, int b) {char t = s[a];s[a] = s[b];s[b] = t; } queue<StateAndLevel> q; set<char *,cmp> allState; void addNei(char *state,int pos,int newPos,int le) {char *new_state=(char*)malloc(9* sizeof(char));strcpy(new_state,state);swap(new_state,pos,newPos);if(allState.find(new_state)==allState.end()){allState.insert(new_state);q.push(StateAndLevel(new_state,le+1,newPos));} } int main() {q.push(StateAndLevel(start,0,0));allState.insert(start);while(!q.empty()){StateAndLevel sal=q.front();char *state=sal.state;int le=sal.level,pos0=sal.pos0,new_pos;if(strcmp(state,target)==0){cout << le << endl;return 0;}new_pos=(pos0-1+9)%9;addNei(state,pos0,new_pos,le);new_pos=(pos0-2+9)%9;addNei(state,pos0,new_pos,le);new_pos=(pos0+1+9)%9;addNei(state,pos0,new_pos,le);new_pos=(pos0+2+9)%9;addNei(state,pos0,new_pos,le);q.pop();}return 0; }總結
以上是生活随笔為你收集整理的2017年第八届蓝桥杯 - 省赛 - C/C++大学A组 - B. 跳蚱蜢的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2017/Province_Java_B
- 下一篇: 迷宫问题 POJ - 3984