#include <iostream> #include <stdio.h> #include <string.h> #include <stdlib.h> using namespace std; int a,b,c,s,e; int v[101][101]; struct node { int x,y,ans; }q[100001],t,f; void FILI(int xx,int yy,int zz,int i) { if(i==0) { f.x=a; f.y=yy; if(v[f.x][f.y]==0) { f.ans=zz+1; q[e++]=f; v[f.x][f.y]=1; } } else if(i==1) { f.x=xx; f.y=b; if(v[f.x][f.y]==0) { f.ans=zz+1; q[e++]=f; v[f.x][f.y]=1; } } } void POUR(int xx,int yy,int zz,int i) { if(i==2) { f.x=0; f.y=yy; if(v[f.x][f.y]==0) { f.ans=zz+1; q[e++]=f; v[f.x][f.y]=1; } } else if(i==3) { f.x=xx; f.y=0; if(v[f.x][f.y]==0) { f.ans=zz+1; q[e++]=f; v[f.x][f.y]=1; } } } void D(int xx,int yy,int zz,int i) { if(i==4) { if(xx+yy>=a) { f.x=a; f.y=yy+xx-a; } else { f.x=xx+yy; f.y=0; } if(v[f.x][f.y]==0) { f.ans=zz+1; q[e++]=f; v[f.x][f.y]=1; } } else if(i==5) { if(xx+yy>=b) { f.y=b; f.x=xx+yy-b; } else { f.y=xx+yy; f.x=0; } if(v[f.x][f.y]==0) { f.ans=zz+1; q[e++]=f; v[f.x][f.y]=1; } } } void bfs() { e=0; s=0; memset(v,0,sizeof(v)); v[0][0]=1; t.x=0; t.y=0; t.ans=0; q[e++]=t; while(s<e) { t=q[s++]; if(t.x==c||t.y==c) { printf("%d\n",t.ans); return ; } for(int i=0;i<6;i++) { if(i==0) FILI(t.x,t.y,t.ans,i); else if(i==1) FILI(t.x,t.y,t.ans,i); else if(i==2) POUR(t.x,t.y,t.ans,i); else if(i==3) POUR(t.x,t.y,t.ans,i); else if(i==4) D(t.x,t.y,t.ans,i); else if(i==5) D(t.x,t.y,t.ans,i); } } printf ("impossible\n"); } int main() { while(~scanf("%d%d%d",&a,&b,&c)) { bfs(); } return 0; }
原文:http://www.cnblogs.com/zhangmingcheng/p/3876250.html