Professional Documents
Culture Documents
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
classQueue
{
public:
Queue()
:head(NULL),tail(NULL)
{
}
voidenqueue(inti)
{
if(head==NULL)
head=tail=newNode(i,NULL);
else
tail=tail>next=newNode(i,NULL);
}
intdequeue()
{
Node*old=head;
head=head>next;
inti=old>i;
deleteold;
returni;
}
intisEmpty()
{
return(head==NULL);
}
~Queue()
{
while(!isEmpty())
dequeue();
}
private:
structNode
{
inti;
Node*next;
Node(intiP,Node*nextP)
:i(iP),next(nextP)
{
}
}*head,*tail;
}iQueue;
constintMAX=100;
constintMAX_I=(MAX+1)*(MAX+1);
intN,M,k,n,m;
intdistance[MAX_I];
intprev[MAX_I];
intnmToI(intn,intm)
{
returnn*(M+1)+m;
}
intiToN(inti)
{
returni/(M+1);
}
intiToM(inti)
{
returni%(M+1);
}
voidtrace(inti)
{
if(i>0)
trace(prev[i]);
cout<<""<<iToN(i)<<"|"<<iToM(i)<<"\n";
}
voidtest(intn,intm,intn1,intm1)
{
if(n1<0||n1>N||m1<0||m1>M)
return;
inti1=nmToI(n1,m1);
if(distance[i1]!=0)
return;
inti=nmToI(n,m);
distance[i1]=distance[i]+1;
prev[i1]=i;
iQueue.enqueue(i1);
}
intsolve()
{
n=m=0;
distance[0]=1;
iQueue.enqueue(0);
while(!iQueue.isEmpty())
{
inti=iQueue.dequeue();
intn=iToN(i);
intm=iToM(i);
if(n==k||m==k||n+m==k)
returni;
//emptyoutajug
test(n,m,0,m);
test(n,m,n,0);
//fillajug
test(n,m,N,m);
test(n,m,n,M);
//pouronetoanotheruntilsourceisempty
test(n,m,0,n+m);
test(n,m,n+m,0);
//pouronetoanotheruntildestinationisfull
test(n,m,nM+m,M);
test(n,m,N,mN+n);
}
return1;
}
voidmain()
{
clrscr();
cout<<"Pleaseenterthenumberofgallonsinfirstjug:";
cin>>N;
cout<<"Pleaseenterthenumberofgallonsinsecondjug:";
cin>>M;
cout<<"Pleaseenterthevol.ofwatertobeleftfinally:";
cin>>k;
inti=solve();
cout<<"JUG1"<<"JUG2\n";
cout<<"\n";
if(i==1)
cout<<0<<"\n";
else
{
cout<<distance[i]<<"\n";
trace(i);
}
cout<<1<<"\n";
getch();
}