ZOJ water jugs problem
Solution with loop:
#include <iostream> using namespace std; int main(){ int m,n,k,r; while(std::cin>>m>>n>>k){ r=n-m; cout<<"fill B"<<endl; cout<<"pour B A"<<endl; while(r!=k){ if(r<m){ r=n-(m-r); cout<<"empty A"<<endl<<"pour B A"<<endl<<"fill B"<<endl<<"pour B A"<<endl; }else{ r=r-m; cout<<"empty A"<<endl<<"pour B A"<<endl; } } cout<<"success"<<endl; } }
It seems to be the right solution, but ZOJ gave "Time limit Exceeded" error; I searched on the interenet about this problem, someone suggests that it may result from "cout/cin" in c++, so I tried printf in C, but it still generates error. Then I tried Iteration method:
#include <iostream> using namespace std; void operation(int m,int n,int mnow,int nnow,int k){ if(nnow==k) return; if(nnow>(m-mnow)){ nnow=nnow-(m-mnow); cout<<"pour B A"<<endl; if(nnow==k) return; cout<<"empty A"<<endl; mnow=0; }else{ mnow=nnow; nnow=n; cout<<"pour B A"<<endl<<"fill B"<<endl; } operation(m,n,mnow,nnow,k); } int main(){ int m,n,k,mnow,nnow; while(cin>>m>>n>>k){ mnow=0; nnow=n; cout<<"fill B"<<endl; operation(m,n,mnow,nnow,k); cout<<"success"<<endl; } }
Finally, it is accepted!!!!!