九度OJ-1457:非常可樂
阿新 • • 發佈:2018-12-30
本題也是轉化為狀態建立解答樹並剪枝,然後進行廣度優先搜尋。
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 <iostream> #include <queue> #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<Ans> 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"<<endl; continue; } //initiate while (!q.empty()) q.pop(); for (int i=0;i<=S;i++){ for (int j=0;j<=N;j++){ for (int k=0;k<=M;k++){ mark[i][j][k]=false; } } } q.push(Ans(S,0,0,0)); mark[S][0][0]=true; find=false; //shift while (!q.empty()){ //judge if ((q.front().s==0&&q.front().n==q.front().m)||(q.front().n==0&&q.front().s==q.front().m) ||(q.front().m==0&&q.front().s==q.front().n)){//find or not cout<<q.front().t<<endl; find=true; break; } //shift if (q.front().s!=0){//S shift //S->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"<<endl; } return true; }