这篇文章用的bfs,昨天还看到一个大神的数论推导,太强了:https://blog.csdn.net/v5zsq/article/details/52097459
这一道题由于没有给出杯子的具体量度,只是给出了最大容量,故每次两个杯子之间的状态为两种:
1. s1全部倒入s2中;(s1现在的液体和s2中已有的液体之和小于等于s2的容积)
2.s1倒入s2中,s1中仍有剩余;(s1已有的液体与s2中已有的液体之和超过了s2的容积,故s1有剩余)
只有三个容器,因此如果满足条件(假设a->b,需要a中有液体,而b未满)即可互相倾倒,因此某一步最多可以转移出六种状态:即a->b,a->s,b->a,b->s,s->a,s->b;
那既然需要计算最小步数就需要一个step数组记录状态,对于未出现的状态step[this.a][this.a]=step[last.a][last.b]+1;
show u code:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
using namespace std;
typedef long long ll;
const int inf=0x3f3f3f3f;
const double epos=1e-8;
const int maxn=109;
//记录状态出现与否;因为题目明确指出s==a+b,故两个维度表示a,b第三个维度s一定是确定的;
int flag[maxn][maxn];
//记录步数,对于未出现的状态step[this.a][this.a]=step[last.a][last.b]+1;
int step[maxn][maxn];
int s,a,b;//将a看做大杯子,当然也可以不管只不过是bfs退出条件那里多了一条语句而已;
struct Node{
int a,b,s;
};//分别表示当前杯子中的量;
queue<Node>q;
void init(){
memset(flag,0,sizeof(flag));
memset(step,0,sizeof(step));
while(!q.empty())
q.pop();
}
int bfs(){
init();
Node chushi,now,in;//now是每次从队列中弹出的状态,in是要进入队列的状态;
chushi.a=0,chushi.b=0,chushi.s=s;
flag[chushi.a][chushi.b]=1;
q.push(chushi);
while(!q.empty()){
now=q.front();
q.pop();
if(now.a==s/2&&now.s==s/2)
return step[now.a][now.b];
if(now.a&&now.b<b){
if(now.a+now.b<b){
in.a=0;
in.s=now.s;
in.b=now.a+now.b;
}
else{
in.b=b;
in.s=now.s;
in.a=now.a-b+now.b;
}
if(flag[in.a][in.b]==0){
step[in.a][in.b]=step[now.a][now.b]+1;
q.push(in);
flag[in.a][in.b]=1;
}
}//a->b
if(now.a&&now.s<s){
if(now.a+now.s<s){
in.a=0;
in.s=now.a+now.s;
in.b=now.b;
}
else{
in.s=s;
in.a=now.a-s+now.s;
in.b=now.b;
}
if(flag[in.a][in.b]==0){
step[in.a][in.b]=step[now.a][now.b]+1;
q.push(in);
flag[in.a][in.b]=1;
}
}//a->s
if(now.b&&now.a<a){
if(now.a+now.b<a){
in.b=0;
in.a=now.a+now.b;
in.s=now.s;
}
else{
in.a=a;
in.b=now.b-a+now.a;
in.s=now.s;
}
if(flag[in.a][in.b]==0){
step[in.a][in.b]=step[now.a][now.b]+1;
q.push(in);
flag[in.a][in.b]=1;
}
}//b->a
if(now.b&&now.s<s){
if(now.b+now.s<s){
in.a=now.a;
in.b=0;
in.s=now.b+now.s;
}
else{
in.a=now.a;
in.b=now.b-s+now.s;
in.s=s;
}
if(flag[in.a][in.b]==0){
step[in.a][in.b]=step[now.a][now.b]+1;
q.push(in);
flag[in.a][in.b]=1;
}
}//b->s
if(now.s&&now.a<a){
if(now.s+now.a<a){
in.s=0;
in.b=now.b;
in.a=now.a+now.s;
}
else{
in.b=now.b;
in.a=a;
in.s=now.s-a+now.a;
}
if(flag[in.a][in.b]==0){
step[in.a][in.b]=step[now.a][now.b]+1;
q.push(in);
flag[in.a][in.b]=1;
}
}//s->a
if(now.s&&now.b<b){
if(now.s+now.b<b){
in.a=now.a;
in.b=now.s+now.b;
in.s=0;
}
else{
in.a=now.a;
in.b=b;
in.s=now.s-b+now.b;
}
if(flag[in.a][in.b]==0){
step[in.a][in.b]=step[now.a][now.b]+1;
q.push(in);
flag[in.a][in.b]=1;
}
}//s->b
}
return -1;
}
int main(){
while(scanf("%d%d%d",&s,&a,&b)!=EOF&&(s+a+b)!=0){
if(a<b) swap(a,b);
if(s&1){
printf("NO\n");
continue;
}
int ttt=bfs();
if(ttt==-1)
printf("NO\n");
else
printf("%d\n",ttt);
}
return 0;
}