本题也是转化为状态建立解答树并剪枝,然后进行广度优先搜索。
Debug记录:
①找了很久,最后发现是mark数组的初始化除了问题,原代码如下:
for (int i=1;i<=S;i++){
for (int j=1;j<=N;j++){
for (int k=1;k<=M;k++){
mark[i][j][k]=false;
}
}
}
下标明明要从0开始遍历的,空杯子也是一种状态。所以以后初始化标记数组的时候记得无论如何从0开始,即使[0]不会被用到。
大家一定觉的运动以后喝可乐是一件很惬意的事情,但是seeyou却不这么认为。因为每次当seeyou买了可乐以后,阿牛就要求和seeyou一起分享这一瓶可乐,而且一定要喝的和seeyou一样多。但seeyou的手中只有两个杯子,它们的容量分别是N 毫升和M 毫升 可乐的体积为S (S<101)毫升(正好装满一瓶) ,它们三个之间可以相互倒可乐 (都是没有刻度的,且 S==N+M,101>S>0,N>0,M>0) 。聪明的ACMER你们说他们能平分吗?如果能请输出倒可乐的最少的次数,如果不能输出"NO"。
三个整数 : S 可乐的体积 , N 和 M是两个杯子的容量,以"0 0 0"结束。
如果能平分的话请输出最少要倒的次数,否则输出"NO"。
7 4 3 4 1 3 0 0 0
NO 3
#include
#include
#define MAXSIZE 100
using namespace std;
struct Ans{
int s,n,m,t;
Ans(){
}
Ans(int s,int n,int m,int t){
this->s=s;
this->n=n;
this->m=m;
this->t=t;
}
};
bool mark[MAXSIZE+1][MAXSIZE+1][MAXSIZE+1];
queue q;
void A2B(int A,int B,int &a,int &b,Ans &ans){
if (a+b>B){//Òç³ö
a-=B-b;
b=B;
}
else{
b+=a;
a=0;
}
ans.t++;
if (mark[ans.s][ans.n][ans.m]==false){
mark[ans.s][ans.n][ans.m]=true;
q.push(ans);
}
}
int main(){
int S,N,M;
Ans tempAns;
bool find;
while (cin>>S>>N>>M,S&&N&&M){
//odd impossible
if (S%2==1){
cout<<"NO"<N
tempAns=q.front();
A2B(S,N,tempAns.s,tempAns.n,tempAns);
//S->M
tempAns=q.front();
A2B(S,M,tempAns.s,tempAns.m,tempAns);
}
if (q.front().n!=0){//N shift
//N->S
tempAns=q.front();
A2B(N,S,tempAns.n,tempAns.s,tempAns);
//N->M
tempAns=q.front();
A2B(N,M,tempAns.n,tempAns.m,tempAns);
}
if (q.front().m!=0){//M shift
//M->S
tempAns=q.front();
A2B(M,S,tempAns.m,tempAns.s,tempAns);
//M->N
tempAns=q.front();
A2B(M,N,tempAns.m,tempAns.n,tempAns);
}
q.pop();
}
if (find==false)
cout<<"NO"<