答案对但是TLE,玄关(之前贴错代码了)
查看原帖
答案对但是TLE,玄关(之前贴错代码了)
989143
Nahida_Official楼主2024/11/5 20:38
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int MANX=1e5;
struct node{
	int x;
	int step;
	node(int a,int b){
		x=a;
		step=b;
	}
};
inline int read(){
	int x=0,f=1;
	char ch=getchar();
	while(ch<'0'||ch>'9'){
		if(ch=='-') f=-1,ch=getchar();
	}
	while(ch>='0'&&ch<='9'){
		x=x*10+ch-48;
		ch=getchar();
	}
	return x*f;
}
void out(int x){
	if(x<0) putchar('-'),x=-x;
	if(x<10) putchar(x+'0');
	else out(x/10),putchar(x%10+'0');
}
int t,x,y;
int bfs(int x,int y){
	bool markk[MANX];
	memset(markk,0,sizeof(markk));
	queue<node> op;
	int nxt;
	op.push(node(x,0));
	markk[x]=1;
	while(!op.empty()){
		node head=op.front();
		op.pop();
		for(int i=0;i<3;i++){
			int cur=head.x;
			if(i==1) nxt=cur+1;
			else if(i==2) nxt=cur-1;
			else nxt=cur*2;
			if(nxt>0 && nxt<=100000 && markk[nxt]==0){
				op.push(node(nxt,head.step+1));
				markk[nxt]=1;
				if(nxt==y){
					return head.step+1;
				}
			}
		}
	}
}
int main(){
	t=read();
	while(t--){
		x=read();
		y=read();
		if(x==y){
		    out(0);
			continue;
		} 
		out(bfs(x,y));
		printf("\n");
	}
	return 0;
}
2024/11/5 20:38
加载中...