BFS求调
查看原帖
BFS求调
846661
ARIS1_0楼主2023/9/5 13:49
#include<bits/stdc++.h>
#define ll long long
using namespace std;
inline int read(){
	int x=0,w=1;
	char ch=0;
	while(ch<'0'||ch>'9'){
		if(ch=='-')w=-1;
		ch=getchar();
	}
	while(ch>='0'&&ch<='9'){
		x=x*10+(ch-'0');
		ch=getchar();
	}
	return x*w;
}
void write(int x){
	if(x<0){
		putchar('-');
		x=-x;
	}
	static int sta[35];
	int top=0;
	do{
		sta[top++]=x%10,x/=10;
	}while(x);
	while(top)putchar(sta[--top]+'0');
}
queue<int>q;
int t,x,y,mp[100005];
bool vis[100005]={false};
void bfs(){
	while(!q.empty()){
		int now=q.front();
		vis[now]=true;
		q.pop();
		if(now-1>=1&&!vis[now-1]){
			q.push(now-1);
			mp[now-1]=mp[now]+1;
		}
		if(now+1<=100001&&!vis[now+1]){
			q.push(now+1);
			mp[now+1]=mp[now]+1;
		}
		if(now*2<=100001&&!vis[now*2]){
			q.push(now*2);
			mp[now*2]=mp[now]+1;
		}
	}
}
int main(){
	t=read();
	while(t--){
		memset(mp,0,sizeof(mp));
		memset(vis,0,sizeof(vis));
		while(!q.empty())q.pop();
		x=read();
		y=read();
		q.push(x);
		bfs();
		write(mp[y]);
		puts("");
	}
	return 0;
}
2023/9/5 13:49
加载中...