您的位置:首页 > 其它

ZOJ water jugs problem

2014-01-06 16:54 204 查看
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!!!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: