POJ Catch That Cow
阿新 • • 發佈:2022-03-30
題面
思路
bfs模擬最短路,需要一個額外的陣列儲存這個點是否走過,搜尋到這個點就跳出
#pragma GCC optimize(2) #include<iostream> #include<algorithm> #include<queue> typedef long long ll; using namespace std; struct yuu{ int whw; int time; };\\定義佇列元素型別 queue<struct yuu> quu; bool vis[100009];\\標記是否走過 int lef,cow,MIN; void bfs(int wh,int tim) { if(wh<0||wh>100000||vis[wh]==true)\\超界退出 return ; if(wh==cow)\\搜尋到就標記 { vis[wh]=true; MIN=tim; return; } vis[wh]=true;\\標記並且入隊 struct yuu dd; dd.whw=wh,dd.time=tim; quu.push(dd); } int main() { std::ios::sync_with_stdio(false); std::cin.tie(0); cin>>lef>>cow; struct yuu bb; bb.time=0,bb.whw=lef; vis[lef]=true;\\初始位置預設走過 quu.push(bb); while(!quu.empty()) { bb=quu.front(); bfs(bb.whw-1,bb.time+1); bfs(bb.whw+1,bb.time+1); bfs(bb.whw*2,bb.time+1); quu.pop(); } cout<<MIN<<endl; return 0; }