AcWing 1100. 抓住那头牛
原题链接
简单
作者:
minux
,
2020-05-21 11:54:22
,
所有人可见
,
阅读 596
python bfs
class Solution:
def main(self, n:int, k:int):
N, INF=int(2e5+5), int(2e5)
dist=[-1 for _ in range(N)]
def op(i, v):
if i==0: return v+1
elif i==1: return v-1
elif i==2:
if 2*v>INF: return INF
else: return 2*v
def bfs(x):
q=[x]
dist[x]=0
while q:
v=q[0]
q.pop(0)
for i in range(3):
nv=op(i, v)
if 0<=nv and nv<=INF and dist[nv]==-1:
dist[nv]=dist[v]+1
if nv==k: return
else: q.append(nv)
bfs(n)
print(dist[k])
if __name__ == '__main__':
n, k = map(int, input().split())
sol=Solution()
sol.main(n, k)
c++ bfs
#include <bits/stdc++.h>
using namespace std;
const int N=2e5+5;
int n, k;
int dist[N];
int main(){
memset(dist, -1, sizeof dist);
cin>>n>>k;
function<int(int, int)> op=[](int i, int v){
if(i==0) return v+1;
else if(i==1) return v-1;
else if(i==2){
if(2*v>=2e5) return (int)2e5;
else return 2*v;
}
};
function<void(int)> bfs=[&](int x){
queue<int> q;
q.push(x);
dist[x]=0;
while(!q.empty()){
int v=q.front();
q.pop();
for(int i=0; i<3; ++i){
int nv=op(i, v);
if(0<=nv<=2e5 && dist[nv]==-1){
if(nv==k) {dist[k]=dist[v]+1; return;}
else{
dist[nv]=dist[v]+1;
q.push(nv);
}
}
}
}
};
bfs(n);
cout<<dist[k]<<endl;
return 0;
}