wikioi 1226 倒水问题

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

有两个无刻度标志的水壶,分别可装 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;
}






评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值