有2个杯子,分别为5升和9升,在一个水池里有无限的水源,怎么才能在水池里拿到6升水呢
#include<iostream> using namespace std; void print1(int,int,int); void print2(int,int,int); int main(){ int a, b, need; cout<<"输入两个杯子的容量及需要量出的水量:\n"; cin>>a>>b>>need; print1(a,b,need); print2(a,b,need); system("pause"); return 0; } void print1(int a, int b, int need){ int tmp,min,max,curMin,curMax; cout<<"\n\n逆容差算法:小杯子没水就装满水,大杯子水满了就倒掉,小杯子有水就往大杯子倒。然后判断大杯子水是否满足条件,不满足就继续\n\n"; if(a > b){ tmp = a; a = b; b = tmp; } min = a;//小杯子的容量 max = b;//大杯子的容量 curMin = 0;//当前小杯子里面有多少水 curMax = 0;//当前大杯子里面有多少水 //循环判断大杯子的水是否满足条件 cout<<"当前小杯子有"<<curMin<<"升水,当前大杯子有"<<curMax<<"升水\n"; while(curMax != need){ if(curMin == 0){ cout<<"小杯子没水了,装满水\n"; curMin = min; } else if (curMax == max){ cout<<"大杯子水满了,全倒掉\n"; curMax = 0; } else{ //将小杯子的水倒给大杯子,判断能倒多少水过去 tmp = max - curMax; tmp = tmp > curMin ? curMin : tmp; cout<<"将小杯子的水倒"<<tmp<<"升给大杯子\n"; curMax += tmp; curMin -= tmp; } cout<<"当前小杯子有"<<curMin<<"升水,当前大杯子有"<<curMax<<"升水\n"; } cout<<"当前大杯子的水满足条件,程序退出\n\n"; } void print2(int a, int b, int need){ int tmp,min,max,curMin,curMax; cout<<"\n\n顺容差算法:大杯子没水就装满水,小杯子水满了就倒掉,大杯子有水就往小杯子倒。然后判断大杯子水是否满足条件,不满足就继续\n\n"; if(a > b){ tmp = a; a = b; b = tmp; } min = a;//小杯子的容量 max = b;//大杯子的容量 curMin = 0;//当前小杯子里面有多少水 curMax = 0;//当前大杯子里面有多少水 //循环判断大杯子的水是否满足条件 cout<<"当前小杯子有"<<curMin<<"升水,当前大杯子有"<<curMax<<"升水\n"; while(curMax != need){ if(curMax == 0){ cout<<"大杯子没水了,装满水\n"; curMax = max; } else if (curMin== min){ cout<<"小杯子水满了,全倒掉\n"; curMin = 0; } else{ //将大杯子的水倒给小杯子,判断能倒多少水过去 tmp = min- curMin; tmp = tmp > curMax ? curMax : tmp; cout<<"将大杯子的水倒"<<tmp<<"升给小杯子\n"; curMax -= tmp; curMin += tmp; } cout<<"当前小杯子有"<<curMin<<"升水,当前大杯子有"<<curMax<<"升水\n"; } cout<<"当前大杯子的水满足条件,程序退出\n\n"; }
时间: 2024-10-09 01:07:53