P1588 [USACO07OPEN] Catch That Cow S bfs最短路
作者:
多米尼克領主的致意
,
2024-05-03 16:14:00
,
所有人可见
,
阅读 2
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
typedef pair<int, int>pii;
int x, y;
int t;
//int vis[N];
int ans;
int mn;
bool st[N];
void bfs()
{
queue<pii>q;
q.push({x, 0});
while(q.size())
{
auto t = q.front();
int zb = t.first;
int step = t.second;
if(zb == y)
{
cout << step << endl;
break;
}
q.pop();
for(int i = 1;i <= 3;i++)
{
if(i == 1)
{
if(st[zb + 1] || zb + 1 >= y)continue;
q.push({zb + 1, step + 1});
st[zb + 1] = true;
}
if(i == 2)
{
if(zb - 1 <= 0 || st[zb - 1])continue;
q.push({zb - 1, step + 1});
st[zb - 1] = true;
}
if(i == 3)
{
if(2 * zb > y || st[2 * zb])
continue;
q.push({zb * 2, step + 1});
st[zb * 2] = true;
}
}
}
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> t;
while(t--)
{
cin >> x >> y;
bfs();
memset(st, 0, sizeof st);
}
}