BFS蓝题 20分 求助大佬
查看原帖
BFS蓝题 20分 求助大佬
246331
mystic_qwq楼主2023/11/16 23:25

record

code here:

#include<iostream>
#include<bitset>
#include<queue>
#include<cmath>
#include<stdio.h>
using namespace std;
bitset<100000> j;
bool flg=0;
struct num{int n,t;};
int func(int n,int k,int x){
  int p10=pow(10,k),low=n%p10,high=n-low;
  return low+x*p10+(high<<1)+(high<<3);
}
int rev(int n,int x){
  int p10=pow(10,x),n1=(n/p10)%10,n2=(((n<<1)+(n<<3))/p10)%10;
  return n-((n1<<1)+(n1<<3)+n2)*p10/10+((n2<<1)+(n2<<3)+n1)*p10/10;
}
int del(int n,int x){
  int p10=pow(10,x),down=n%p10,up=(n-down)/10,down1=n%(p10/10);
  //printf("up=%d down=%d down1=%d\n",up,down,down1);
  return up+down1;
}
int main(){
  ios::sync_with_stdio(0),cin.tie(NULL);
  int s,m,Len;
  cin>>s>>m;
  Len=(int)log10(s);
  //cout<<"Len="<<Len<<'\n';
  //printf("func(12356,2,4)=%d\n",func(12356,2,4));
  //printf("func(1357,1,6)=%d\n",func(1357,1,6));
  //printf("func(1357,2,4)=%d\n",func(1357,2,4));
  //printf("func(1357,3,2)=%d\n",func(1357,3,2));
  //printf("rev(12356,2)=%d\n",rev(12356,2));
  //printf("del(12345,2)=%d\n",del(12345,2));
  //printf("del(12356,5)=%d\n",del(12356,5));
  while(m--){
    j.reset();flg=0;
    int t;cin>>t;
    if(s==t){puts("0");continue;}
    queue<num> Q;
    Q.push({s,0});j[s]=1;
    do{
      num f=Q.front();Q.pop();if(!f.n)continue;
      int len=(int)log10(f.n);
      //cout<<"Front:"<<f.n<<' '<<"len:"<<len<<'\n';
      int tmp2;
      if(len<Len){
        //printf("Get in [func]: Len=%d len=%d\n",Len,len);
        for(int k=1,tmp=f.n,tmp1=f.n/10;k<=len;++k,tmp=tmp1,tmp1/=10){
          //printf("k=%d tmp=%d tmp1=%d\n",k,tmp,tmp1);
          int t1=tmp1%10,t2=tmp%10;
          if(t1-t2>1||t2-t1>1)
            for(int i=min(t1,t2)+1;i<max(t1,t2);++i){if((tmp2=func(f.n,k,i))==t){cout<<f.t+1<<'\n';flg=1;goto _;}if(!j[tmp2])/*printf("[func]In:%d\n",tmp2),*/j[tmp2]=1,Q.push({tmp2,f.t+1});}
        }
      }
      for(int i=1;i<=len;++i){if((tmp2=rev(f.n,i))==t){cout<<f.t+1<<'\n';flg=1;goto _;}if(!j[tmp2])j[tmp2]=1/*,printf("[rev]In:%d\n",tmp2)*/,Q.push({tmp2,f.t+1});}
      for(int i=1;i<=len+1;++i){if((tmp2=del(f.n,i))==t){cout<<f.t+1<<'\n';flg=1;goto _;}if(!j[tmp2])j[tmp2]=1/*,printf("[del]In:%d\n",tmp2)*/,Q.push({tmp2,f.t+1});}
      _:;
    }while(!Q.empty()&&!flg);
    if(!flg)cout<<"-1\n";
  }
}

2023/11/16 23:25
加载中...