wikioi 1226 倒水问题

来源:互联网 发布:网络的重要性的名言 编辑:程序博客网 时间:2024/06/11 02:01

来源:http://www.wikioi.com/problem/1226/

 8人推荐  收藏 发题解

有两个无刻度标志的水壶,分别可装 x 升和 y 升 ( x,y 为整数且均不大于 100 )的水。

设另有一水 缸,可用来向水壶灌水或接从水壶中倒出的水, 两水壶间,水也可以相互

倾倒。已知 x 升壶为空 壶, y 升壶为空壶。问如何通过倒水或灌水操作, 用最少步数

能在x或y升的壶中量出 z ( z ≤ 100 )升的水 来。

一行,三个数据,分别表示 x,y 和 z;

一行,输出最小步数 ,如果无法达到目标,则输出"impossible"

3 22 1

14



题意:略


题解: BFS   模板题,直接上代码


AC代码:

#include<iostream>using namespace std;const int Max=5000000;int water[2],z,exdir=0,nodedir=0;struct Node{int cup[3],step;} map[Max]={0},temp;bool check(Node x){for(int i=0;i<=exdir;i++) if(temp.cup[0]==map[i].cup[0]&&temp.cup[1]==map[i].cup[1])  return false;  return true;}int main(){for(int i=0;i<2;i++)cin>>water[i];cin>>z;  map[0].step=0;while(nodedir<=exdir&&exdir<Max){for(int i=0;i<3;i++)   //i向j倒水 for(int j=0;j<3;j++){temp=map[nodedir];if(i==j||(!temp.cup[i]&&i!=2)||(temp.cup[j]==water[j]&&j!=2)) continue; //不能倒 if(i==2)  temp.cup[j]=water[j]; //水缸向杯子加水else if(j==2) temp.cup[i]=0;  //将杯子中的水倒光 else { int tempw=min(temp.cup[i],water[j]-temp.cup[j]); temp.cup[i]-=tempw; temp.cup[j]+=tempw; }      temp.step++;  if(temp.cup[0]==z||temp.cup[1]==z){  cout<<temp.step<<endl;  return 0;  }  if(check(temp)){  map[++exdir]=temp;  }}nodedir++; } cout<<"impossible"<<endl; return 0;}






0 1
原创粉丝点击