Simple BFs. No optimization is required.
The storage status of a struct array is used. The values a, B, and move indicate the number of balls and the number of moves in case a and case B respectively.
Pay attention to the handling of special circumstances and Determination of impossible situations:
(1) The difference between two numbers is an odd number. For example, assume a <B, the number of moving balls is A, and the difference is 2a.
The first step in the final state is that the number of two boxes is equal, and the difference is equal to 0, so it is impossible to achieve this.
(2) The difference between two numbers is 4-plus 2, but the initial number of balls is an even number.
Based on the above, it is impossible to export data.
(3) The same as before.
--This is hard to process.-The data range is there.-vis [2 ^ 31] [2 ^ 31] cannot be opened --
A lazy method (also the method used for benzene slag) is to limit the number of traversal cases, I set 150000.
Fortunately, sgu data is relatively weak-(or any of the situations will be repeated before 150000? Unknown)
Code:
#include "stdio.h"#include "string.h"#include "stdlib.h"const int MAXMOVE=150000;struct status{int a,b,move;};int BFS(int A,int B){status q[MAXMOVE+10];int flag=0,i,j,front,rear,tmp;front=0;rear=0;q[0].a=A;q[0].b=B;q[0].move=0;if(!q[0].a||!q[0].b){return 0;}if((q[0].a+q[0].b)%2){return -1;}else{while(1){if((q[0].a%2==0)&&((q[0].a-q[0].b)%4)){return -1;break;}if(rear>MAXMOVE){return -1;break;}//printf("Front=%d,Rear=%d.\n",front,rear);tmp=rear;while(front<=tmp){//printf("***front=%d.\n",front);//Move Balls from B To A.if(q[front].b>=q[front].a){rear++;q[rear].a=2*q[front].a;q[rear].b=q[front].b-q[front].a;//printf("******Rear = %d: A = %d, B = %d.\n",rear,q[rear].a,q[rear].b);//getchar();q[rear].move=q[front].move+1;if(!q[rear].a||!q[rear].b){return q[rear].move;flag=1;break;}}//Move Balls from A To B.if(q[front].a>=q[front].b){rear++;q[rear].b=2*q[front].b;q[rear].a=q[front].a-q[front].b;q[rear].move=q[front].move+1;//printf("*******Rear = %d: A = %d, B = %d.\n",rear,q[rear].a,q[rear].b);//getchar();if(!q[rear].a||!q[rear].b){return q[rear].move;flag=1;break;}}front++;}if(flag)break;}}}int main(){int ans,A,B;scanf("%d%d",&A,&B);ans=BFS(A,B);printf("%d\n",ans);return 0;}